views:

950

answers:

4

Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc. Thanks.

+1  A: 

I found this one. http://mail.python.org/pipermail/python-list/2000-June/037460.html that does the rounding for you.

Preet Sangha
+10  A: 

This grabs subdirectories:

import os
start_path = '.'
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
    for f in filenames:
        fp = os.path.join(dirpath, f)
        total_size += os.path.getsize(fp)

And a oneliner for fun using os.listdir (Does not include sub-directories):

sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)])

Reference:

os.path.getsize - Gives the size in bytes

os.walk

Updated To use os.path.getsize, this is clearer than using the os.stat().st_size method.

Thanks to ghostdog74 for pointing this out!

os.stat - *st_size* Gives the size in bytes. Can also be used to get file size and other file related information.

monkut
+1 but the oneliner doesn't return a valid result because it is not recursive
luc
Yeah, it's just for the flat directory case.
monkut
For real fun you can do a recursive size in one line: sum( os.path.getsize(os.path.join(dirpath,filename)) for dirpath, dirnames, filenames in os.walk( PATH ) for filename in filenames )
driax
A: 

monknut answer is good but it fails on broken symlink, so you also have to check if this path really exists

if os.path.exists(fp):
    total_size += os.stat(fp).st_size
troex
+1  A: 

for getting the size of one file, there is os.path.getsize()

>>> import os
>>> os.path.getsize("/path/file")
35L

its reported in bytes.

ghostdog74