How to get a file system information using Python?


Filesystem information, in Python, is defined as the attributes and metadata linked with a file or directory, such as its name, size, timestamps, permissions, ownership, and type. There are various modules in Python like os and os.path to work with the file system and fetch this information. Obtaining access to filesystem information allows developers to work with files and directories, carry out operations like creation and deletion, and take informed decisions within their code.

To fetch file system information using Python, you can utilize the os module; it provides several functions for interacting with the operating system. In particular, the os.statvfs() function from the os module can be used to retrieve information about a file system. Let's explore in detail how to use this function with a stepwise explanation and a code example:

Importing the Required Module

import os

Retrieving File System Information

Next, you can proceed to use the os.statvfs() function to fetch file system information. This function accepts the path to a file or directory as an argument and returns a os.statvfs_result object that gives as output various attributes representing the file system's properties.

# Specify the path to the file or directory
path = '/path/to/file_or_directory'

# Retrieve the file system information
fs_info = os.statvfs(path)

Access File System Attributes

Once the os.statvfs_result object is obtained, different attributes can be accessed to obtain specific file system information. Some of the commonly used attributes are as follows:

fs_favail − The number of available file nodes in the file system.

fs_files − The total number of file nodes in the file system.

f_bsize − The optimal file system block size.

f_frsize − The fundamental file system block size.

f_blocks − The total number of blocks in the file system.

f_bfree − The number of free blocks in the file system.

Example

Let us consider an example that demonstrates accessing and printing some of these attributes 

# Print some file system information
print("File System Information:")
print("Available File Nodes:", fs_info.f_favail)
print("Total File Nodes:", fs_info.f_files)
print("Optimal Block Size:", fs_info.f_bsize)

If the above code and the previous code are run as one snippet, for a certain file, we may get the following output

Output

File System Information:
Available File Nodes: 6859438
Total File Nodes: 7208960
Optimal Block Size: 4096

Executing the Code

The code is saved as a Python file, and executed. You ensure that '/path/to/file_or_directory' is replaced with the actual path to the file or directory for which you wish to extract the file system information.

By making use of the os.statvfs() function and having access to the appropriate attributes of the returned object, you can gather valuable insights about the file system in question.

Getting Disk Usage Information

In this example, we make use of the shutil module's disk_usage() function to get the disk usage statistics of a file system. This function gives a named tuple as output that has the attributes like the total, used, and free disk space in bytes.

Example

import shutil

# Specify the path to the file or directory
path = '/path/to/file_or_directory'

# Get disk usage information
usage = shutil.disk_usage(path)

# Print disk usage information
print("Disk Usage Information:")
print("Total Space:", usage.total)
print("Used Space:", usage.used)

print("Free Space:", usage.free)

Output

If the above code is executed, for a certain directory we may get the following output

Disk Usage Information:
Total Space: 115658190848
Used Space: 26008670208
Free Space: 89632743424

Making Use of the Psutil Library

Here, we learn about the psutil library; it provides a cross-platform way to extract system information, including file system-related details. Next, we use the psutil.disk_usage() function to fetch the disk usage statistics.

Example

import psutil

# Specify the path to the file or directory
path = '/path/to/file_or_directory'

# Get disk usage information
usage = psutil.disk_usage(path)

# Print disk usage information
print("Disk Usage Information:")
print("Total Space:", usage.total)
print("Used Space:", usage.used)
print("Free Space:", usage.free)

Output

If the above code is executed, for a certain file, we may get the following output

Disk Usage Information:
Total Space: 115658190848
Used Space: 26009186304
Free Space: 89632227328

In both examples, we have specified the path to the file or directory for which we want to extract the file system information. We then call the proper function (shutil.disk_usage() or psutil.disk_usage()) with the path as an argument to get the disk usage information. Finally, we obtain access to the attributes of the returned object and print the relevant details.

You should not forget to replace '/path/to/file_or_directory' with the actual path you want to examine. You can execute these code examples to retrieve the file system information and gain deep and useful insights into the disk usage of the specified location.

Making Use of the Os Module

In this code example, we make use of the os.statvfs() function from the os module; we use it to retrieve file system information. This function gives details about the file system linked with the specified path, including the total size, available space, and much more.

Example

In this code, we utilize the os.statvfs() function to obtain a file system statistics object. We then fetch specific attributes of the object to calculate the total and available space in bytes. At the very end, we print the file system information to the console.

import os

# Specify the path to the file or directory
path = '/path/to/file_or_directory'

# Get file system information
stat = os.statvfs(path)

# Calculate the total and available space in bytes
total_space = stat.f_frsize * stat.f_blocks
available_space = stat.f_frsize * stat.f_bavail

# Print file system information
print("File System Information:")
print("Total Space:", total_space)
print("Available Space:", available_space)

Output

If the above code is run, for a certain file, we may get the following output

File System Information:
Total Space: 115658190848
Available Space: 89632002048

Making Use of the Subprocess Module

Here, we use the subprocess module to run a system command and capture or take a snapshot of the file system information from the output. This approach is dependent on executing a command-line utility like df and parsing the output to extract the relevant information.

Example

In the code below, we utilize the subprocess.check_output() function to run and execute the df command and capture its output as a string. We then split the output into lines and extract the required information by splitting and accessing specific elements. Finally, we display the file system information on the console.

import subprocess

# Specify the path to the file or directory
path = '/path/to/file_or_directory'

# Execute the 'df' command and capture the output
command = ['df', path]
output = subprocess.check_output(command).decode('utf-8')

# Extract the file system information from the output
lines = output.strip().split('\n')
header = lines[0].split()
data = lines[1].split()
total_space = int(data[1])
available_space = int(data[3])

# Print file system information
print("File System Information:")
print("Total Space:", total_space)
print("Available Space:", available_space)

Output

If the above code is run, for a certain file, we may get the following output

File System Information:
Total Space: 112947452
Available Space: 87530992

In short, we have seen various approaches to finding filesystem information using Python. Apart from the code examples discussed, the additional examples provide alternative ways to obtain file system information using Python, giving you flexibility in choosing the method that best suits your requirements and use cases.

From this article you have learned hands-on methods of practicing given code examples, thus retrieving file system information and gaining insights into the disk usage and availability of any specified location using Python.

Updated on: 20-Jul-2023

615 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements