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
I'm a little late (and new) here but I chose to use the subprocess module and the 'du' command line with Linux to retrieve an accurate value for folder size in MB. I had to use if and elif for root folder because otherwise subprocess raises error due to non-zero value returned.
Some of the approaches suggested so far implement a recursion, others employ a shell or will not produce neatly formatted results. When your code is one-off for Linux platforms, you can get formatting as usual, recursion included, as a one-liner. Except for the
print
in the last line, it will work for current versions ofpython2
andpython3
:is simple, efficient and will work for files and multilevel directories:
A bit late after 5 years, but because this is still in the hitlists of search engines, it might be of help...
I'm using python 2.7.13 with scandir and here's my one-liner recursive function to get the total size of a folder:
https://pypi.python.org/pypi/scandir
The accepted answer doesn't take into account hard or soft links, and would count those files twice. You'd want to keep track of which inodes you've seen, and not add the size for those files.
A little late to the party but in one line provided that you have glob2 and humanize installed. Note that in Python 3, the default
iglob
has a recursive mode. How to modify the code for Python 3 is left as a trivial exercise for the reader.Here is a recursive function (it recursively sums up the size of all subfolders and their respective files) which returns exactly the same bytes as when running "du -sb ." in linux (where the "." means "the current folder"):