Search code examples
pythondirectoryfilesizeaccess-denied

python access denied while computing c drive size


I'm using the following function to compute the size of a directory using Python

def get_path_size(path):
    total_size = 0
    for path, dirs, files in os.walk(path):
        for f in files:
            fp = os.path.join(path, f)
            total_size += os.path.getsize(fp)

    return total_size

I have tested it with many directories, but it doesn't work when I try to compute the size of the C drive

print(get_path_size("C:/"))

OSError: [WinError 1920] The system cannot access the file: 'C:/Users\asus\AppData\Local\Microsoft\WindowsApps\MicrosoftEdge.exe'

How can I compute a directory's size without having admin rights ?


Solution

  • In the particular case you look for the usage of a drive, I'd suggest you use shutil:

    import shutil
    shutil.disk_usage("C:")
    

    Yields:

    usage(total=498439548928, used=204051705856, free=294387843072)
    

    Notice that there is a slight discrepancy with the value reported in the GUI, because of reserved space on the drive not taken into account, so it might not be suitable for your need.