在我重新发明这个特殊的轮子之前,有没有人有一个很好的用Python计算目录大小的例程?如果该例程能以Mb/Gb等格式格式化大小,那就太好了。
当前回答
这将遍历所有子目录;文件大小总和:
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')
和一个在线的乐趣使用操作系统。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,这比使用os.stat()更清楚。st_size方法。
感谢ghostdog74指出这一点!
操作系统。stat - st_size以字节为单位给出大小。也可用于获取文件大小等文件相关信息。
import os
nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())
更新2018
如果您使用的是Python 3.4或更早版本,那么您可以考虑使用第三方scandir包提供的更有效的walk方法。在Python 3.5及以后版本中,此包已合并到标准库和操作系统中。行走得到了相应的性能提升。
更新2019
最近我越来越多地使用pathlib,这里有一个pathlib解决方案:
from pathlib import Path
root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())
其他回答
import os
def get_size(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
if os.path.exists(fp):
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size # in megabytes
谢谢monkut & troex!
递归的一行代码:
def getFolderSize(p):
from functools import partial
prepend = partial(os.path.join, p)
return sum([(os.path.getsize(f) if os.path.isfile(f) else getFolderSize(f)) for f in map(prepend, os.listdir(p))])
python3.5 +
from pathlib import Path
def get_size(folder: str) -> int:
return sum(p.stat().st_size for p in Path(folder).rglob('*'))
用法::
In [6]: get_size('/etc/not-exist-path')
Out[6]: 0
In [7]: get_size('.')
Out[7]: 12038689
In [8]: def filesize(size: int) -> str:
...: for unit in ("B", "K", "M", "G", "T"):
...: if size < 1024:
...: break
...: size /= 1024
...: return f"{size:.1f}{unit}"
...:
In [9]: filesize(get_size('.'))
Out[9]: '11.5M'
下面是一个递归函数(它递归地总结所有子文件夹及其各自文件的大小),返回的字节与在linux中运行“du -sb .”时完全相同(其中“。”表示“当前文件夹”):
import os
def getFolderSize(folder):
total_size = os.path.getsize(folder)
for item in os.listdir(folder):
itempath = os.path.join(folder, item)
if os.path.isfile(itempath):
total_size += os.path.getsize(itempath)
elif os.path.isdir(itempath):
total_size += getFolderSize(itempath)
return total_size
print "Size: " + str(getFolderSize("."))
不管怎样……树命令免费完成所有这些工作:
tree -h --du /path/to/dir # files and dirs
tree -h -d --du /path/to/dir # dirs only
我喜欢Python,但到目前为止,这个问题最简单的解决方案不需要新的代码。