Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 /dev/sda2 is mounted on /home, and /dev/mapper/foo is 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/foo I would like to obtain the size of the partition and the free space available (either in bytes or approximately in megabytes).

like image 506
Federico A. Ramponi Avatar asked Nov 23 '10 19:11

Federico A. Ramponi


People also ask

How much free space do I have Linux?

The simplest way to find the free disk space on Linux is to use df command. The df command stands for disk-free and quite obviously, it shows you the free and available disk space on Linux systems. With -h option, it shows the disk space in human-readable format (MB and GB).

How do I check storage space on Linux?

That command is df -H. The -H switch is for human-readable format. The output of df -H will report how much space is used, available, percentage used, and the mount point of every disk attached to your system (Figure 1).

How do I check disk space on Ubuntu?

To check the free disk space and disk capacity with System Monitor: Open the System Monitor application from the Activities overview. Select the File Systems tab to view the system's partitions and disk space usage. The information is displayed according to Total, Free, Available and Used.


1 Answers

This doesn't give the name of the partition, but you can get the filesystem statistics directly using the statvfs Unix system call. To call it from Python, use os.statvfs('/home/foo/bar/baz').

The relevant fields in the result, according to POSIX:

unsigned long f_frsize   Fundamental file system block size.  fsblkcnt_t    f_blocks   Total number of blocks on file system in units of f_frsize.  fsblkcnt_t    f_bfree    Total number of free blocks.  fsblkcnt_t    f_bavail   Number of free blocks available to                           non-privileged process. 

So to make sense of the values, multiply by f_frsize:

import os statvfs = os.statvfs('/home/foo/bar/baz')  statvfs.f_frsize * statvfs.f_blocks     # Size of filesystem in bytes statvfs.f_frsize * statvfs.f_bfree      # Actual number of free bytes statvfs.f_frsize * statvfs.f_bavail     # Number of free bytes that ordinary users                                         # are allowed to use (excl. reserved space) 
like image 198
Mechanical snail Avatar answered Oct 05 '22 05:10

Mechanical snail