Python-获取文件使用的总字节数

Python-获取文件使用的总字节数,python,file,filesize,filenotfoundexception,Python,File,Filesize,Filenotfoundexception,我正在尝试获取所有文件使用的总字节数 到目前为止,我得到的是以下信息 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 但是,运行此操作时,会弹出

我正在尝试获取所有文件使用的总字节数

到目前为止,我得到的是以下信息

 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”

这可能有帮助:

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

请阅读更多有关
os.walk
工作原理的信息。然后,错误消息将变得更加清晰。提示:您可以尝试使用
os.path.join()
来建立文件的完整路径。如果您使用的是最新的windows,请注意正确处理硬链接,否则SxS缓存将显示错误的数字,因为它包含很多硬链接。PermissionError告诉您运行脚本的用户不允许访问该文件。以可以访问文件的用户身份运行脚本,或者使用try…except捕获异常而不退出脚本。这正是我想要的,谢谢:)