Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

จะคำนวณขนาดไดเร็กทอรีโดยใช้ Python ได้อย่างไร?


เพื่อให้ได้ขนาดของไดเร็กทอรี คุณจะต้องเดินไปตามแผนผังไดเร็กทอรีทั้งหมดและเพิ่มขนาดของแต่ละไฟล์ ในการดำเนินการนี้ คุณสามารถใช้ฟังก์ชัน os.walk() และ os.path.getsize()

ตัวอย่าง

import os
total_size = 0
start_path = '.'  # To get size of current directory
for path, dirs, files in os.walk(start_path):
    for f in files:
        fp = os.path.join(path, f)
        total_size += os.path.getsize(fp)
print("Directory size: " + str(total_size))

หากคุณใช้ระบบปฏิบัติการ *NIX คุณสามารถเรียกคำสั่ง du โดยใช้โมดูลกระบวนการย่อยได้ เนื่องจากง่ายกว่าวิธีข้างต้นมาก

ตัวอย่างเช่น

import subprocess
path = '.'
size = subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')
print("Directory size: " + size)

ผลลัพธ์

การรันโปรแกรมใดโปรแกรมหนึ่งจะให้ผลลัพธ์:

Directory size: 1524664