【发布时间】:2013-05-30 14:14:59
【问题描述】:
将目录的大小与 Unix 和 python 进行比较时,我得到的结果略有不同(“磁盘使用率”小 5%)。为什么 ? (我所有的子文件夹都是可读的;我在 Mac OSX Mountain lion,python 版本 2.7.2 下工作)
这是我的代码:
import os, sys
from commands import getstatusoutput
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)
total_size += os.path.getsize(fp)
return total_size/1024
def get_size2(start_path = '.'):
cmd = "du -ks "+start_path # result in blocks of 1024 bytes
code_err, output = getstatusoutput(cmd)
return int(output.split()[0])
print get_size()
# 306789
print get_size2()
# 321328
提前感谢您的回答,
埃里克。
【问题讨论】:
-
将字节大小相加并除以 1024 与得到使用的 1024 个块的总数不同(想想有 1024 个文件的一个字节。他们总共使用 1024 个字节 = 1 个块,但是实际上每个文件使用一个 1024 块,所以实际使用的空间是 1024^2)。尝试修改
getsize来计算每个文件使用的1024块的数量,结果应该是一样的。 -
样式说明:
commands模块已弃用。在你的情况下,你真的应该使用subprocess.check_output -
你是对的。我猜我的机器块大小是 4096,si 我将行 total_size += 替换为 total_size += (os.path.getsize(fp)+4096)/4096 * 4 \n\n某些目录的结果相同,但其他目录的结果仍然略低(此处:316140)
标签: python macos directory os.walk du