簡體   English   中英

如何查找目錄及其所有子目錄中所有文件的大小?

[英]How to find the size of all files in a directory and all its sub-directories?

我試圖打印目錄及其所有子目錄中所有文件的名稱和大小,但它只打印第一個目錄中文件的名稱和大小,而不打印子目錄中的文件的名稱和大小。 任何幫助將不勝感激。

import os
path = os.getcwd()
walk_method = os.walk(path)
while True:
    try:
        p, sub_dir, files = next(walk_method)
        break
    except:
        break
size_of_file = [
    (f, os.stat(os.path.join(path, f)).st_size)
    for f in files
]
for sub in sub_dir:
    i = os.path.join(path, sub)
    size = 0
    for k in os.listdir(i):
        size += os.stat(os.path.join(i, k)).st_size
    size_of_file.append((sub, size))
for f, s in sorted(size_of_file, key = lambda x: x[1]):
    print("{} : {}MB".format(os.path.join(path, f), round(s/(1024*1024), 3)))

我希望打印當前目錄和所有子目錄中所有文件的名稱和文件大小。

文檔包含一些您可能選擇遵循的有用示例代碼。 永遠循環/next()/中斷方法可以工作,我敢肯定,但它不是慣用的,而且這種風格不會提高代碼的可維護性。

from pathlib import Path
import os

total = 0
for root, dirs, files in os.walk("."):
    for file in files:
        path = Path(root) / file
        print(path)
        total += path.stat().st_size

print(f"Total of {total} bytes.")

我認為 pathlib 在這里很棒,有很多方法可以解決這個問題,但一個簡單的例子是這樣的:

from pathlib import Path

dir = "."
paths = list(Path(dir).glob('**/*'))
for path in paths:
    if path.is_file():
        print(f"{path.name}, {path.lstat().st_size}")

您不需要循環,但為了簡單起見,在本例中我只是使用了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM