du命令和Python函数之间的文件大小差异

时间:2016-02-11 20:21:30

标签: python bash recursion size du

我有一个脚本,我每晚运行以获取存储在我服务器上特定目录中的东西。这是我用于核心部分的功能:

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            try:
                fp = os.path.join(dirpath, f)
                total_size += os.path.getsize(fp)
                print str(total_size)+" bytes / "+str(size(total_size))+" counted"+" <------------ current position: "+start_path+" : "+f
                for location in locations_dict:
                    if locations_dict[location][1] != "":
                        print str(location)+": "+str(size(locations_dict[location][1]))
            except OSError, e:
                print e
    return total_size

出于某种原因,我在手动运行时获得了不同的值

$ du -hc [path to dir]

使用Python我得到20551043874445字节(转换为20.5 TB)。我得到du 28 TB(我现在没有-h重新运行以获取字节值)。

很明显,Python函数缺少一些东西,但我不确定是什么或如何。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

du以512字节块显示大小。如果文件大小不是512的倍数,则du向上舍入。要在Python中获取等效值,而不是使用os.path.getsize(),请使用os.stat()并使用结果的st_blocks属性。

total_size += os.stat(fp).st_blocks * 512;
相关问题