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