Python os.fstat() Method



The Python fstat() method returns information about a file associated with the file descriptor. A file descriptor is a unique identifier for a file that is currently open by the process. Here is the information returned by fstat method −

  • st_dev − ID of device containing file

  • st_ino − inode number

  • st_mode − protection

  • st_nlink − number of hard links

  • st_uid − user ID of owner

  • st_gid − group ID of owner

  • st_rdev − device ID (if special file)

  • st_size − total size, in bytes

  • st_blksize − blocksize for filesystem I/O

  • st_blocks − number of blocks allocated

  • st_atime − time of last access

  • st_mtime − time of last modification

  • st_ctime − time of last status change

The os.fstat() method works similarly to the "os.stat()" method but is used when you have a file descriptor rather than a file path.

Syntax

Syntax of fstat() method is as follows −

os.fstat(fd)

Parameters

The Python os.fstat() method accepts a single parameter −

  • fd − This is the file descriptor for which system information is to be returned.

Return Value

The Python os.fstat() method returns information about a file associated with the file descriptor.

Example

The following example shows the usage of fstat() method. The result will contain a "stat_result" object with information about the file.

#!/usr/bin/python
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Now get the touple
info = os.fstat(fd)
print ("Printing the Info of File :", info)

# Close opened file
os.close( fd)

When we run above program, it produces following result −

Printing the Info of File : os.stat_result(st_mode=33277, st_ino=1054984, st_dev=2051, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1713157516, st_mtime=1713157516, st_ctime=1713157517)

Example

In the following example, we are displaying the UID and GID of a given file using the fstat() method.

#!/usr/bin/python
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
info = os.fstat(fd)

# Now get uid of the file
print ("UID of the file :%d" % info.st_uid)

# Now get gid of the file
print ("GID of the file :%d" % info.st_gid)

# Close opened file
os.close( fd)
print("File closed successfully!!")

On running the above program, it will show the below result −

UID of the file :1000
GID of the file :1000
File closed successfully!!
python_files_io.htm
Advertisements