Python: List Directories and Sizes

痞子三分冷 提交于 2020-06-28 04:24:09

问题


I'm trying to write some Python code that will traverse each directory in the current working directory and report the total size (in bytes) under each directory, regardless of how deep each directory itself goes.

This is just for a learning project, I realize there are already other ways to get this information through the shell. Here's some code I have so far:

# 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

So the output will hopefully look something like this:

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

total        226,452 bytes

回答1:


This will list the sizes of the directories in a given directory, plus the total:

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('.')

Output:

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

total  205,072 bytes



回答2:


You should look at os.path.walk.



来源:https://stackoverflow.com/questions/5680165/python-list-directories-and-sizes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!