2011-04-15 53 views
1

我想寫一些Python代碼,它將遍歷當前工作目錄中的每個目錄,並報告每個目錄下的總大小(以字節爲單位),而不管每個目錄本身的深度如何。Python:列表目錄和大小

這只是一個學習項目,我意識到已經有其他方法通過shell獲取這些信息。下面是一些代碼,我到目前爲止有:

# get name of current working directory 
start_directory = os.getcwd() 

# create dictionary to hold the size of each folder in 
# the current working directory 
top_level_directory_sizes = {} 

# initialize directory 
for i in os.listdir(start_directory): 
    if os.path.isdir(i): 
     top_level_directory_sizes[i] = 0 

# traverse all paths from current working directory 
for dirpath, dirnames, filenames in os.walk(start_directory): 

    for f in filenames: 
     fp = os.path.join(dirpath, f) 
     #increment appropriate dictionary element: += os.path.getsize(fp) 

for k,v in top_level_directory_sizes.iteritems(): 
    print k, v 

所以輸出將希望是這個樣子:

algorithms 23,754 bytes 
articles  1,234 bytes 
books  123,232 bytes 
images  78,232 bytes 

total  226,452 bytes 

回答

3

這將列出目錄的大小在給定的目錄,加上總:

import locale 
import os 

locale.setlocale(locale.LC_ALL, "") 

def get_size(state, root, names): 
    paths = [os.path.realpath(os.path.join(root, n)) for n in names] 
    # handles dangling symlinks 
    state[0] += sum(os.stat(p).st_size for p in paths if os.path.exists(p)) 

def print_sizes(root): 
    total = 0 
    paths = [] 
    state = [0] 
    n_ind = s_ind = 0 
    for name in sorted(os.listdir(root)): 
     path = os.path.join(root, name) 
     if not os.path.isdir(path): 
      continue 

     state[0] = 0 
     os.path.walk(path, get_size, state) 
     total += state[0] 
     s_size = locale.format('%8.0f', state[0], 3) 
     n_ind = max(n_ind, len(name), 5) 
     s_ind = max(s_ind, len(s_size)) 
     paths.append((name, s_size)) 

    for name, size in paths: 
     print name.ljust(n_ind), size.rjust(s_ind), 'bytes' 
    s_total = locale.format('%8.0f', total, 3) 
    print '\ntotal'.ljust(n_ind), s_total.rjust(s_ind), 'bytes' 

print_sizes('.') 

輸出:

% python dirsizes.py 
bar 102,672 bytes 
foo 102,400 bytes 

total 205,072 bytes 
+0

它不會遞歸等犯規給文件夾的大小說三個層次下。 – rapadura 2012-09-18 15:22:52

2

你應該看看os.path.walk