Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tính kích thước thư mục bằng Python?


Để lấy kích thước thư mục, bạn phải duyệt toàn bộ cây thư mục và cộng kích thước từng file. Dùng os.walk() và os.path.getsize().

Ví dụ

import os
total_size = 0
start_path = '.'  # Lấy kích thước thư mục hiện tại
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))

Nếu bạn dùng *NIX OS, có thể gọi lệnh du qua module subprocess, cách này đơn giản hơn:

Ví dụ

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

Kết quả

Chạy một trong hai chương trình sẽ cho ra:

Directory size: 1524664