Get file information in Python



Some times you will need to get some information about a file, last access/modification, creation, size, permises...

Let's supose we have the file 'example.txt' inside the path '/my/path', and we want to know some stuff about this file.

os.stat() function

You can check the official documentation at Python Docs: os.stat()

Now we'll see the example

import os
import time
 
# The result of the function is an array, we can get it inside 1 variable or get each stat in different vars
 
# Array
file_status_array = os.stat('/my/path/example.txt')
 
# vars
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat('/my/path/example.txt')
 
# We can format access, modification and creation dates with time.ctime()
time.ctime(ctime)  # Output: 'Tue Dec 30 08:35:53 2014'
time.ctime(atime)  # Output: 'Tue Jan 13 09:15:29 2015'
time.ctime(mtime)  # Output: 'Mon Jan 12 08:57:29 2015'

The explanation of the array and vars is:

mode - protection bits,
ino - inode number,
dev - device,
nlink - number of hard links,
uid - user id of owner,
gid - group id of owner,
size - size of file, in bytes,
atime - time of most recent access,
mtime - time of most recent content modification,
ctime - platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)
If you have any doubt don't hesitate commenting !

Leave a comment

You have to wait to comment again. Wait Time: