在我重新发明这个特殊的轮子之前,有没有人有一个很好的用Python计算目录大小的例程?如果该例程能以Mb/Gb等格式格式化大小,那就太好了。
当前回答
你可以这样做:
import commands
size = commands.getoutput('du -sh /path/').split()[0]
在这种情况下,我没有在返回之前测试结果,如果你想要,你可以用commands.getstatusoutput检查它。
其他回答
使用库sh: du模块执行:
pip install sh
import sh
print( sh.du("-s", ".") )
91154728 .
如果您想传递asterix,请使用此处描述的glob。
要转换human readable中的值,请使用humanize:
pip install humanize
import humanize
print( humanize.naturalsize( 91157384 ) )
91.2 MB
不管怎样……树命令免费完成所有这些工作:
tree -h --du /path/to/dir # files and dirs
tree -h -d --du /path/to/dir # dirs only
我喜欢Python,但到目前为止,这个问题最简单的解决方案不需要新的代码。
如果你使用的是Windows操作系统,你可以:
通过以下方式安装pywin32模块:
PIP安装pywin32
然后编码如下:
import win32com.client as com
def get_folder_size(path):
try:
fso = com.Dispatch("Scripting.FileSystemObject")
folder = fso.GetFolder(path)
size = str(round(folder.Size / 1048576))
print("Size: " + size + " MB")
except Exception as e:
print("Error --> " + str(e))
到目前为止,建议的一些方法实现了递归,其他方法使用shell或不会生成格式整齐的结果。当您的代码对于Linux平台是一次性的,您可以像往常一样获得格式化,包括递归,作为一行程序。除了最后一行的输出,它将适用于当前版本的python2和python3:
du.py
-----
#!/usr/bin/python3
import subprocess
def du(path):
"""disk usage in human readable format (e.g. '2,1GB')"""
return subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')
if __name__ == "__main__":
print(du('.'))
简单,高效,将工作于文件和多级目录:
$ chmod 750 du.py
$ ./du.py
2,9M
接受的答案不考虑硬链接或软链接,并将这些文件计算两次。您可能希望跟踪已看到的inode,而不是为这些文件添加大小。
import os
def get_size(start_path='.'):
total_size = 0
seen = {}
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
try:
stat = os.stat(fp)
except OSError:
continue
try:
seen[stat.st_ino]
except KeyError:
seen[stat.st_ino] = True
else:
continue
total_size += stat.st_size
return total_size
print get_size()