[英]Most efficient way to determine the size of a directory in Python
os.walk 有一個有用的例子:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end=" ")
print(sum(getsize(join(root, name)) for name in files), end=" ")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
盡管注意到os.walk
通過切換到os.scandir
在 Python 3.5 中變得更快,但這並沒有提到它仍然是 Windows 上的次優實現。
https://www.python.org/dev/peps/pep-0471/確實描述了這一點並且幾乎是正確的。 但是,它建議使用遞歸。 在處理任意文件夾結構時,這不會很好地工作,因為您會很快達到 Python 遞歸限制(您將只能迭代文件夾結構最多 1000 個文件夾深度,如果您從根目錄開始文件系統的數量不一定不現實。真正的限制實際上不是 1000。它是 1000 - 當您 go 運行此 function 時,您的 Python 調用深度。如果您這樣做是為了通過 883238686555 響應 web 服務請求的業務邏輯層,很容易接近這個限制也不是不現實的。
以下代碼片段在所有操作系統上都應該是最佳的,並且可以處理您扔給它的任何文件夾結構。 Memory 的使用顯然會隨着您遇到的文件夾的增加而增加,但據我所知,您對此無能為力,因為您必須以某種方式跟蹤需要 go 的位置。
def get_tree_size(path):
total_size = 0
dirs = [path]
while dirs:
next_dir = dirs.pop()
with os.scandir(next_dir) as it:
for entry in it:
if entry.is_dir(follow_symlinks=False):
dirs.append(entry.path)
else:
total_size += entry.stat(follow_symlinks=False).st_size
return total_size
使用collections.deque
可能會加快操作速度,而不是在這里簡單地使用列表,但我懷疑很難編寫一個基准來用磁盤速度來顯示它們今天的速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.