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
Here is a one liner that does it recursively (recursive option available as of Python 3.5):
Thanks monkut & troex! This works really good!
for getting the size of one file, there is os.path.getsize()
its reported in bytes.
When size of the sub-directories is computed, it should update its parent's folder size and this will go on till it reaches the root parent.
The following function computes the size of the folder and all its sub-folders.
For what it's worth... the tree command does all of this for free:
I love Python, but by far the simplest solution to the problem requires no new code.
The following script prints directory size of all sub-directories for the specified directory. It also tries to benefit (if possible) from caching the calls of a recursive functions. If an argument is omitted, the script will work in the current directory. The output is sorted by the directory size from biggest to smallest ones. So you can adapt it for your needs.
PS i've used recipe 578019 for showing directory size in human-friendly format (http://code.activestate.com/recipes/578019/)
Sample output:
EDIT: moved null_decorator above, as user2233949 recommended