[英]File size discrepancy between du command and Python function
我有一個腳本,每晚運行一次,以將大量內容存儲在服務器上的特定目錄中。 這是我用於該核心部分的功能:
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函數缺少某些內容,但是我不確定是什么或如何。 有任何想法嗎?
du
以512字節塊為單位顯示大小。 如果文件大小不是512的倍數,則du
向上取整。 要在Python中獲得等效值,請使用os.stat()
並使用結果的st_blocks
屬性,而不要使用os.path.getsize()
。
total_size += os.stat(fp).st_blocks * 512;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.