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.
Before I re-invent this particular wheel, has anybody got a nice routine for calculating
Share
This walks all sub-directories; summing file sizes:
And a oneliner for fun using os.listdir (Does not include sub-directories):
Reference:
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.
Update 2018
If you use Python 3.4 or previous then you may consider using the more efficient
walkmethod provided by the third-partyscandirpackage. In Python 3.5 and later, this package has been incorporated into the standard library andos.walkhas received the corresponding increase in performance.Update 2019
Recently I’ve been using
pathlibmore and more, here’s apathlibsolution: