Python: How to Get File Details
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.
1 | import os |
2. os.path.getmtime()
This method returns the last modified date of the file. Again, you’ll need to provide the file path.
1 | import os |
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.
1 | import os |
Alternatively, you can use the os.stat()
function to retrieve all the file details in one go:
1 | import os |
This will return an os.stat_result
object containing various properties, including:
st_mode
: The file type and permissionsst_ino
: The inode numberst_dev
: The device IDst_uid
: The file owner IDst_gid
: The file group IDst_size
: The file size
To access individual properties, you can use the dot notation:
1 | import os |
By utilizing these methods and functions, you can easily retrieve important file details in your Python programs.
tags: [“Python”, “file details”, “os module”, “getsize”, “getmtime”, “getctime”, “stat_result”]