Question

Is there a better way to get the root size instead of using os.walk?

import os    

def get_size( start_path='.' ):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size    

print get_size("C:/")

I'm trying this code(which I got from here), it works fine inside folders, not that fast, but when I try it in the root directory it's super slow or sometimes it crashes [WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect]. Is there a way to get the root size just like left cliking properties in C:\?

EDIT: I tweaked a little bit the code to avoid the errors.

fp = os.path.join(dirpath, f)
try:
    stat = os.stat(fp)
except OSError:
    continue

try:
    seen[stat.st_ino]
except KeyError:
    seen[stat.st_ino] = True
else:
    continue

total_size += stat.st_size

But it still slow as hell. It takes 6~7 minutes to calculate it.

Was it helpful?

Solution 2

First, get pywin32 (the Python for Windows Extensions) from here. Then, you can do this:

>>> import win32api
>>> lpFreeBytesAvailable, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes = win32api.GetDiskFreeSpaceEx('C:\\')
>>> lpTotalNumberOfBytes
300061552640

This value (in bytes) is equal to 279 GB, which is the size of the C drive on my machine. Note, however, the caveats in the documentation (reproduced in this answer with emphasis), which may or may not be relevant to your use case.

OTHER TIPS

You want to access the operating system call to get the free space of a volume.

In Python 3.3 and above it's called shutil.disk_usage. For older versions of Python, on Unix people suggest various things like calling the external df utility, but that won't work on Windows. It seems the best answer is to call the win32 API function GetDiskFreeSpaceEx. Take a look at this email:

https://mail.python.org/pipermail/python-win32/2010-July/010640.html

The code appears below:

from ctypes import c_ulong, byref, windll

freeBytesAvailable = c_ulong()
totalNumberOfBytes = c_ulong()
totalNumberOfFreeBytes = c_ulong()

# Ansi version:
windll.kernel32.GetDiskFreeSpaceExA('c:\\', byref(freeBytesAvailable),
byref(totalNumberOfBytes), byref(totalNumberOfFreeBytes))

You can also call the Unicode version GetDiskFreeSpaceExW if you have a Unicode file name.

If you are looking for a cross-platform solution, you may want to try psutil.

They claim they support:

"… Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures, with Python versions from 2.4 to 3.4 by using a single code base."

I just tried this in a terminal window on a Mac:

>>> import psutil
>>> d = psutil.disk_usage('/')
>>> d.free
230785544192

and it gave me the correct information.
Their website and docs can be found here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top