w3resource

Python: Get information about the file pertaining to the file mode


15. File Mode Information

Write a Python program to get information about the file pertaining to file mode. Print the information - ID of device containing file, inode number, protection, number of hard links, user ID of owner, group ID of owner, total size (in bytes), time of last access, time of last modification and time of last status change.

Sample Solution:

Python Code :

import os
path = 'e:\\testpath\\p.txt'
fd = os.open(path, os.O_RDWR)
info = os.fstat(fd)
print (f"ID of device containing file: {info.st_dev}")
print (f"Inode number: {info.st_ino}")
print (f"Protection: {info.st_mode}")
print (f"Number of hard links: {info.st_nlink}")
print (f"User ID of owner: {info.st_uid}")
print (f"Group ID of owner: {info.st_gid}")
print (f"Total size, in bytes: {info.st_size}")
print (f"Time of last access: {info.st_atime}")
print (f"Time of last modification: {info.st_mtime }")
print (f"Time of last status change: {info.st_ctime }")
os.close( fd)

Sample Output:

ID of device containing file: 1181298613
Inode number: 3096224744097510
Protection: 33206
Number of hard links: 1
User ID of owner: 0
Group ID of owner: 0
Total size, in bytes: 44
Time of last access: 1579262486.6472013
Time of last modification: 1579262516.1362014
Time of last status change: 1579262486.6472013

For more Practice: Solve these Related Problems:

  • Write a Python program to use os.stat() to retrieve and print detailed file mode information, including inode number and device ID.
  • Write a Python script to display a file’s permissions, number of hard links, owner, group, and size in bytes by parsing os.stat() results.
  • Write a Python function that accepts a file path, extracts mode and timestamp information, and prints it in a human-readable format.
  • Write a Python program to compare two files' metadata (like last modification time) using os.stat() and then output the differences.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to alter the owner and the group id of a specified file.
Next: Write a Python program to write a string to a buffer and retrieve the value written, at the end discard buffer memory.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.