Python, how to get the details of a file
By Flavio Copes
Learn how to get the details of a file in Python with the os module, using os.path.getsize() for the size or os.stat() to read its size and modified date.
Given the path to a file, you can get its details, like the size and the last modified date, using the os module from the standard library. There are two ways: individual helper functions for single values, or os.stat() to get everything at once.
The helper functions are:
os.path.getsize()returns the size of the file in bytesos.path.getmtime()returns the file last modified dateos.path.getctime()returns the file metadata change date on Unix systems like macOS and Linux, and the creation date on Windows
Here is an example:
import os
filename = '/Users/flavio/test.txt'
print(os.path.getsize(filename)) # 189
print(os.path.getmtime(filename)) # 1605428773.0
print(os.path.getctime(filename)) # 1605428773.0
The times come back as Unix timestamps, the number of seconds since January 1st, 1970. Not very readable. Convert them with the datetime module:
import os
from datetime import datetime
filename = '/Users/flavio/test.txt'
modified = datetime.fromtimestamp(os.path.getmtime(filename))
print(modified) # 2020-11-15 09:26:13
Getting everything at once with os.stat()
os.stat() returns all the information you need in a concise way:
import os
filename = '/Users/flavio/test.txt'
print(os.stat(filename))
It returns an os.stat_result object:
os.stat_result(st_mode=33252, st_ino=34409711, st_dev=16777224, st_nlink=1, st_uid=501, st_gid=20, st_size=189, st_atime=1605428774, st_mtime=1605428773, st_ctime=1605428773)
We have a lot of information here, including:
st_modethe file type and permissionsst_inothe inode numberst_devthe device idst_uidthe file owner idst_gidthe file group idst_sizethe file size in bytes
You can reach for individual properties:
import os
filename = '/Users/flavio/test.txt'
stats = os.stat(filename)
print(stats.st_size) # 189
print(stats.st_mtime) # 1605428773.0
If you call several of the helper functions on the same file, prefer one os.stat() call instead. Each helper reads the file metadata from disk again, while stats holds everything from a single read.
What if the file doesn’t exist?
All these functions raise a FileNotFoundError if the path doesn’t point to an existing file:
os.path.getsize('/Users/flavio/missing.txt')
# FileNotFoundError: [Errno 2] No such file or directory
If the file might not be there, check first with os.path.exists(), or wrap the call in a try/except FileNotFoundError block and handle the missing file there.
Related posts about python: