Cross-platform space remaining on volume using python

I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?

Asked by: Kelvin785 | Posted: 28-01-2022

Answer 1

import ctypes
import os
import platform
import sys

def get_free_space_mb(dirname):
    """Return folder/drive free space (in megabytes)."""
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value / 1024 / 1024
        st = os.statvfs(dirname)
        return st.f_bavail * st.f_frsize / 1024 / 1024

Note that you must pass a directory name for GetDiskFreeSpaceEx() to work (statvfs() works on both files and directories). You can get a directory name from a file with os.path.dirname().

Also see the documentation for os.statvfs() and GetDiskFreeSpaceEx.

Answered by: Alina522 | Posted: 01-03-2022

Answer 2

Install psutil using pip install psutil. Then you can get the amount of free space in bytes using:

import psutil

Answered by: Edward191 | Posted: 01-03-2022

Answer 3

You could use the wmi module for windows and os.statvfs for unix

for window

import wmi

c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
    print( d.Caption, d.FreeSpace, d.Size, d.DriveType)

for unix or linux

from os import statvfs


Answered by: Adrian305 | Posted: 01-03-2022

Answer 4

If you're running python3:

Using shutil.disk_usage()with os.path.realpath('/') name-regularization works:

from os import path
from shutil import disk_usage

print([i / 1000000 for i in disk_usage(path.realpath('/'))])


total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\\Users\\phannypack'))

print(total_bytes / 1000000) # for Mb
print(used_bytes / 1000000)
print(free_bytes / 1000000)

giving you the total, used, & free space in MB.

Answered by: Julian547 | Posted: 01-03-2022

Answer 5

If you dont like to add another dependency you can for windows use ctypes to call the win32 function call directly.

import ctypes

free_bytes = ctypes.c_ulonglong(0)

ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\\'), None, None, ctypes.pointer(free_bytes))

if free_bytes.value == 0:
   print 'dont panic'

Answered by: Haris385 | Posted: 01-03-2022

Answer 6

From Python 3.3 you can use shutil.disk_usage("/").free from standard library for both Windows and UNIX :)

Answered by: Elian146 | Posted: 01-03-2022

Answer 7

A good cross-platform way is using psutil: (Note that you'll need psutil 0.3.0 or above).

Answered by: Brianna406 | Posted: 01-03-2022

Answer 8

You can use df as a cross-platform way. It is a part of GNU core utilities. These are the core utilities which are expected to exist on every operating system. However, they are not installed on Windows by default (Here, GetGnuWin32 comes in handy).

df is a command-line utility, therefore a wrapper required for scripting purposes. For example:

from subprocess import PIPE, Popen

def free_volume(filename):
    """Find amount of disk space available to the current user (in bytes) 
       on the file system containing filename."""
    stats = Popen(["df", "-Pk", filename], stdout=PIPE).communicate()[0]
    return int(stats.splitlines()[1].split()[3]) * 1024

Answered by: Sam429 | Posted: 01-03-2022

Answer 9

Below code returns correct value on windows

import win32file    

def get_free_space(dirname):
    secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
    return secsPerClus * bytesPerSec * nFreeClus

Answered by: Maddie143 | Posted: 01-03-2022

Answer 10

The os.statvfs() function is a better way to get that information for Unix-like platforms (including OS X). The Python documentation says "Availability: Unix" but it's worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date).

Otherwise, you can use the pywin32 library to directly call the GetDiskFreeSpaceEx function.

Answered by: Elise985 | Posted: 01-03-2022

Answer 11

I Don't know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.

For Windows, there's the GetDiskFreeSpaceEx method in the win32 extensions.

Answered by: Ryan992 | Posted: 01-03-2022

Answer 12

Most previous answers are correct, I'm using Python 3.10 and shutil. My use case was Windows and C drive only ( but you should be able to extend this for you Linux and Mac as well (here is the documentation)

Here is the example for Windows:

import shutil

total, used, free = shutil.disk_usage("C:/")

print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))

Answered by: Blake281 | Posted: 01-03-2022

Similar questions

url - Create a cross-platform protocol helper that runs a python script

I'd like to register a protocol handler, like "myapp:", across OS X, Linux, and Windows so that when someone clicks an URL like "myapp://some/params" in a web browser, a Python script will be called and passed in those params. Obviously, this would require something being installed on each machine to enable it, but just...

exception - Is there a cross-platform way of getting information from Python's OSError?

On a simple directory creation operation for example, I can make an OSError like this: (Ubuntu Linux) >>> import os >>> os.mkdir('foo') >>> os.mkdir('foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 17] File exists: 'foo' Now I can catch that error like this: >>> import os ...

Cross-platform way to get PIDs by process name in python

Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using python or jython? I want something like pidof but in python. (I don't have pidof anyway.) I can't parse /proc because it might be unavailable (on HP-UX). I do not want to run os.pop...

user interface - Cross-platform gui toolkit for deploying Python applications

Building on: Merits: 1 - ease of design / integration - learning curve 2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web 3 - python...

Is there a cross-platform python low-level API to capture or generate keyboard events?

I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "", so that every time some program asks me for my email address I just need to type Ctrl-@. I know such programs already exist, and ...

python - WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order

I'm learning wxPython so most of the libraries and classes are new to me. I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure that the buttons are in the correct order for each platform. Does wxPython provide functiona...

Change process priority in Python, cross-platform

I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal. I found this: Set Process Priority In Windows - ActiveState But I'm looking for a cross-platform solution.

python - Cross-platform subprocess with hidden window

I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux: ValueError: startupinfo is only supported on Windows platforms Is there a simpler way than creating a separate Popen command for each OS? if os.nam...

python - Cross-platform help viewer with search functionality

I am looking for a help viewer like Windows CHM that basically provides support for adding content in HTML format define Table of Contents decent search It should work on Windows, Mac and Linux. Bonus points for also having support for generating a "plain HTML/javascript" version that can be viewed in any browser (albeit without search support). Language preference: P...

java - Cross-Platform Programming Language with a decent gui toolkit?

For the program idea I have, it requires that the software be written in one binary that is executeable by all major desktop platforms, meaning it needs an interpreted language or a language within a JVM. Either is fine with me, but the programming language has to balance power & simplicity (e.g. Python) I know of wxPython but I have read that it's support on Mac OS X is fairly limited Java sounds good ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python