使用Python计算目录的大小? [英] Calculating a directory's size using Python?
问题描述
在我重新发明这个特殊的轮子之前,有没有人有一个很好的例程来使用Python计算目录的大小?
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.
推荐答案
这会遍历所有子目录,这将是非常好的。 ;总结文件大小:
This walks all sub-directories; summing file sizes:
import os
def get_size(start_path = '.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
print(get_size(), 'bytes')
使用 os.listdir (不包括子目录):
import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))
参考:
- os.path.getsize -以字节为单位
- os.walk
- os.path.islink
- os.path.getsize - Gives the size in bytes
- os.walk
- os.path.islink
更新
要使用 os.path.getsize ,这比使用os.stat()。st_size方法更清晰。
Updated To use os.path.getsize, this is clearer than using the os.stat().st_size method.
感谢ghostdog74指出这一点!
os.stat - st_size 以字节为单位给出大小。还可用于获取文件大小和其他文件相关信息。
os.stat - st_size Gives the size in bytes. Can also be used to get file size and other file related information.
import os
nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())
更新2018
如果您使用Python 3.4或更低版本,则可以考虑使用效率更高的 walk $第三方
scandir
提供的c $ c>方法软件包。在Python 3.5及更高版本中,此软件包已合并到标准库中,并且 os.walk
获得了相应的性能提升。
If you use Python 3.4 or previous then you may consider using the more efficient walk
method provided by the third-party scandir
package. In Python 3.5 and later, this package has been incorporated into the standard library and os.walk
has received the corresponding increase in performance.
更新2019
最近我越来越多地使用 pathlib
,这是 pathlib
解决方案:
Recently I've been using pathlib
more and more, here's a pathlib
solution:
from pathlib import Path
root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())
这篇关于使用Python计算目录的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!