Frage

I'm trying to get the total amount of bytes used by all files.

What I've got so far is the following.

 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

However, when running this, the following error pops up FileNotFoundError: [WinError 2] The system cannot find the file specified: 'hiberfil.sys'

Does anyone know how I can fix this error and correctly calculate the total bytes on the disk?

EDIT: After looking at this some more, I came up with the following code.

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)

however I now get the following error. PermissionError: [WinError 5] Access is denied: 'C:\\ProgramData\Microsoft\Microsoft Antimalware\Scans\History\CacheManager\MpScanCache-1.bin'

War es hilfreich?

Lösung

This may help:

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'))

Prints:

110,058,100,086 bytes in 449,723 files

Or, if it is a permission error, use this:

            try:
                size = os.stat(tgt).st_size
                totalsize = totalsize + size
                filecnt+=1
            except (#Permission Error type...): 
                continue
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top