Python 3 – os.fstat() Method
In Python, the os
module provides a way to interact with the underlying operating system. The os.fstat()
method is a part of the os
module that is used to get the status of a file descriptor. The file descriptor is a unique reference to an open file.
The os.fstat()
method returns an object that contains the status information for the file descriptor passed as an argument. This information includes the file size, the time of last access, the time of last modification, and the time of creation.
Syntax:
os.fstat(file_descriptor)
Parameters:
file_descriptor
: Required. The file descriptor whose status information needs to be obtained.
Return Value:
The os.fstat()
method returns a tuple that contains the status information of the file descriptor in the following format:
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
Here is a brief explanation of the values returned by the os.fstat()
method:
mode
: The mode of the file. This includes the file type (regular file, directory, symbolic link, etc.) and the permissions (read, write, execute) for the owner, group, and others.ino
: The inode number of the file.dev
: The device number of the file system containing the file.nlink
: The number of hard links to the file.uid
: The user id of the owner of the file.gid
: The group id of the owner of the file.size
: The size of the file in bytes.atime
: The time of the last access to the file (in seconds since the epoch).mtime
: The time of the last modification to the file (in seconds since the epoch).ctime
: The time of the creation of the file (in seconds since the epoch).
Here is an example of how to use the os.fstat()
method in Python:
import os
file_descriptor = os.open('example.txt', os.O_RDONLY)
status = os.fstat(file_descriptor)
print(f"Size of the file: {status.st_size} bytes")
print(f"Time of last access: {status.st_atime}")
print(f"Time of last modification: {status.st_mtime}")
os.close(file_descriptor)
Output:
Size of the file: 123 bytes
Time of last access: 1627925466.7303808
Time of last modification: 1627925465.8856504
In this example, we first open the file example.txt
using the os.open()
method with the os.O_RDONLY
flag, which opens the file for reading only. We then pass the resulting file descriptor to the os.fstat()
method to obtain the status information for the file. Finally, we print the size of the file in bytes and the times of the last access and modification, which are all obtained from the returned object.
Conclusion
The os.fstat()
method in Python is a simple but powerful way to obtain the status information for a file descriptor. By using this method, you can easily obtain the size and time-related information for a file, which can be useful in many different contexts.