Python, how to get the details of a file

By

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:

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:

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.

Tagged: Python · All topics
~~~

Related posts about python: