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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
a recursive one-liner:
Admittedly, this is kind of hackish and only works on Unix/Linux.
It matches
du -sb .
because in effect this is a Python bash wrapper that runs thedu -sb .
command.This grabs subdirectories:
And a oneliner for fun using os.listdir (Does not include sub-directories):
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.
Update 2018
If you use Python 3.4 or previous then you may consider using the more efficient
walk
method provided by the third-partyscandir
package. In Python 3.5 and later, this package has been incorporated into the standard library andos.walk
has received the corresponding increase in performance.It is handy:
One-liner you say... Here is a one liner:
Although I would probably split it out and it performs no checks.
To convert to kb see Reusable library to get human readable version of file size? and work it in
You can do something like this :
in this case I have not tested the result before returning it, if you want you can check it with commands.getstatusoutput.