計算目錄大小真的不是Python的強項,因爲在這個崗位解釋說:very quickly getting total size of folder。如果您有權訪問du
和find
,請務必使用該功能。您可以輕鬆地用下面一行顯示每個目錄的大小:
find . -type d -exec du -hs "{}" \;
如果您在蟒蛇這樣堅持,你可能更post-order traversal在os.walk
,通過PableG的建議。但是,使用os.walk
可以在視覺上更清潔,如果效率不爲您提供最因素:
import os, sys
from collections import defaultdict
def walkIt(folder):
for (path, dirs, files) in os.walk(folder):
size = getDirSize(path)
stats = getExtensionStats(files)
# only get the top 3 extensions
print '%s (%s, %s)'%(path, size, stats[:3])
def getExtensionStats(files):
# get all file extensions
extensions = [f.rsplit(os.extsep, 1)[-1]
for f in files if len(f.rsplit(os.extsep, 1)) > 1]
# count the extensions
exCounter = defaultdict(int)
for e in extensions:
exCounter[e] += 1
# convert count to percentage
percentPairs = [(e, 100*ct/len(extensions)) for e, ct in exCounter.items()]
# sort them
percentPairs.sort(key=lambda i: i[1])
return percentPairs
def getDirSize(root):
size = 0
for path, dirs, files in os.walk(root):
for f in files:
size += os.path.getsize(os.path.join(path, f))
return size
if __name__ == '__main__':
path = sys.argv[1] if len(sys.argv) > 1 else '.'
walkIt(path)
你有迄今爲止編寫任何代碼或映射出任何邏輯是什麼?請發佈。 – foosion