pythonlinuxfilesystemsdiskspacevfs

Find size and free space of the filesystem containing a given file


I'm using Python 2.6 on Linux. What is the fastest way:


Solution

  • If you just need the free space on a device, see the answer using os.statvfs() below.

    If you also need the device name and mount point associated with the file, you should call an external program to get this information. df will provide all the information you need -- when called as df filename it prints a line about the partition that contains the file.

    To give an example:

    import subprocess
    df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
    output = df.communicate()[0]
    device, size, used, available, percent, mountpoint = \
        output.split("\n")[1].split()
    

    Note that this is rather brittle, since it depends on the exact format of the df output, but I'm not aware of a more robust solution. (There are a few solutions relying on the /proc filesystem below that are even less portable than this one.)