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
/dev/sda2is mounted on/home, and/dev/mapper/foois mounted on/home/foo. From the string"/home/foo/bar/baz"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
/dev/mapper/fooI would like to obtain the size of the partition and the free space available (either in bytes or approximately in megabytes).
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.
dfwill provide all the information you need — when called asdf filenameit prints a line about the partition that contains the file.To give an example:
Note that this is rather brittle, since it depends on the exact format of the
dfoutput, but I’m not aware of a more robust solution. (There are a few solutions relying on the/procfilesystem below that are even less portable than this one.)