我正在尝试在 Python 中计算文件夹的大小,但结果很奇怪。
这是我的代码片段:
def bestsize(filepath):
""" Return a tuple with 3 values. The first is the file (or folder size). The second and third
have sense only for folder and are the number of files and subdirectories in folder
"""
from os.path import getsize, isdir
if not(isdir(filepath)): return (getsize(filepath), 1, 0)
else:
lf = []
ld = []
for root, dirs, files in os.walk(filepath):
for name in files: lf.append(os.path.join(root, name))
for dir in dirs: ld.append(os.path.join(root, dir))
return (sum(getsize(i) for i in lf), len(lf), len(ld))
我已经对它进行了一些测试,比较了 Windows 资源管理器所说的结果。
我创建了一个名为“temp”的文件夹,其中有一个名为 temp 的子文件夹和一个名为 7 字节的文件ciao.txt
. 临时文件夹为空。如果我执行我的函数,我会发现我的主文件夹大小为 7 个字节。但是使用 Windows Explorer 我获得了 4096 个字节。
我必须为所有子文件夹(也是空的子文件夹)计算默认大小吗?
os 模块中的默认函数getsize
为所有目录返回 0。
编辑:我已经在 NTFS 文件系统分区上测试了我的代码
编辑:谢谢,现在我明白了。我想做的是更好的 dir/ls 命令。我使用使用 getsize 计算的前一个总和,现在我已经理解了它对我来说很好的区别。
Edit2:我已经编辑了放置我最后一个版本的代码。