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
2009-09-08 07:21:50
+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
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
2009-09-08 07:48:15
+1 but the oneliner doesn't return a valid result because it is not recursive
luc
2009-09-08 10:19:12
Yeah, it's just for the flat directory case.
monkut
2009-09-08 10:23:08
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
2010-08-29 20:02:39
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
2009-11-21 22:24:26
+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
2009-11-21 23:57:12