Python - 获取文件占用的总字节数
我正在尝试计算所有文件占用的总字节数。
到目前为止,我写了以下代码。
def getSize(self):
totalsize = 0
size = 0
for root, dirs, files in os.walk(r'C:\\'):
for files in files:
size = os.stat(files).st_size
totalsize = totalsize + size
但是,当我运行这个代码时,出现了一个错误,内容是 FileNotFoundError: [WinError 2] 系统找不到指定的文件: 'hiberfil.sys'
有没有人知道我该如何修复这个错误,并正确计算磁盘上的总字节数?
补充:在进一步研究后,我写了以下代码。
def getSize():
print("Getting total system bytes")
data = 0
for root, dirs, files in os.walk(r'C:\\'):
for name in files:
data = data + getsize(join(root, name))
print("Total system bytes", data)
但是现在我遇到了另一个错误。 PermissionError: [WinError 5] 访问被拒绝: 'C:\\ProgramData\Microsoft\Microsoft Antimalware\Scans\History\CacheManager\MpScanCache-1.bin'
1 个回答
0
这可能会对你有帮助:
import os
import os.path
def getSize(path):
totalsize,filecnt = 0,0
for root, dirs, files in os.walk(path):
for file in files:
tgt=os.path.join(root,file)
if os.path.exists(tgt):
size = os.stat(tgt).st_size
totalsize = totalsize + size
filecnt+=1
return totalsize,filecnt
print '{:,} bytes in {:,} files'.format(*getSize('/Users/droid'))
输出结果是:
110,058,100,086 bytes in 449,723 files
或者,如果是权限错误的话,可以试试这个:
try:
size = os.stat(tgt).st_size
totalsize = totalsize + size
filecnt+=1
except (#Permission Error type...):
continue