When working with files in Python, you may need to retrieve specific details about a file, such as its size, last modified date, and creation date. Luckily, the os module provides several methods to retrieve this information.

To get started, here are a few methods you can use:

1. os.path.getsize()

This method returns the size of the file in bytes. You simply need to pass the file path as an argument.

import os

filename = '/Users/flavio/test.txt'

filesize = os.path.getsize(filename)
print(filesize)

2. os.path.getmtime()

This method returns the last modified date of the file. Again, you’ll need to provide the file path.

import os

filename = '/Users/flavio/test.txt'

last_modified = os.path.getmtime(filename)
print(last_modified)

3. os.path.getctime()

For Unix-like systems (e.g., macOS), this method returns the file creation date, which is equivalent to the last modified date.

import os

filename = '/Users/flavio/test.txt'

creation_date = os.path.getctime(filename)
print(creation_date)

Alternatively, you can use the os.stat() function to retrieve all the file details in one go:

import os

filename = '/Users/flavio/test.txt'

file_stats = os.stat(filename)
print(file_stats)

This will return an os.stat_result object containing various properties, including:

  • st_mode: The file type and permissions
  • st_ino: The inode number
  • st_dev: The device ID
  • st_uid: The file owner ID
  • st_gid: The file group ID
  • st_size: The file size

To access individual properties, you can use the dot notation:

import os

filename = '/Users/flavio/test.txt'

file_stats = os.stat(filename)
print(file_stats.st_size)
print(file_stats.st_mtime)

By utilizing these methods and functions, you can easily retrieve important file details in your Python programs.