Federico A. Ramponi Federico A. Ramponi - 1 year ago 78
Linux Question

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:

  • to determine which partition contains a given directory or file?

    For example, suppose that
    is mounted on
    , and
    is mounted on
    . From the string
    I would like to recover the pair
    ("/dev/mapper/foo", "home/foo")

  • and then, to get usage statistics of the given partition? For example, given
    I would like to obtain the size of the partition and the free space available (either in bytes or approximately in megabytes).

Answer Source

If you 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 = \

If you don't need device name and mount point, going with os.statvfs() will be better (see other answers).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download