In this tutorial, we will explore how to get the metadata of a file in Python. File metadata provides additional context and information about a file, which can be useful for a number of purposes such as file management, data analysis, and automation tasks. Some examples of metadata include file size, creation time, modification time, and file type.
Step 1: Import the Required Libraries
To begin, we need to import the os and time libraries, which provide the necessary functions for working with the file system and handling timestamps. Add the following lines at the beginning of your Python script:
1 2 |
import os import time |
Step 2: Get the Basic File Metadata
Now that we have the necessary libraries imported, we will get the basic file metadata such as file size, creation time, and modification time. To do this, we’ll use the os.path
module and os.stat()
function. First, specify the file path, and then use the following code to extract the metadata:
1 2 3 4 5 6 7 8 9 10 |
file_path = "example.txt" # Get the file size file_size = os.path.getsize(file_path) # Get the file creation time file_creation_time = time.ctime(os.path.getctime(file_path)) # Get the file modification time file_modification_time = time.ctime(os.path.getmtime(file_path)) |
Step 3: Print the Basic File Metadata
Now that we have retrieved the file metadata, let’s print the information to the console to see the results. Add the following lines of code to your script:
1 2 3 4 |
print("File path:", file_path) print("File size:", file_size, "bytes") print("File creation time:", file_creation_time) print("File modification time:", file_modification_time) |
Running the script should produce output similar to the following:
File path: example.txt File size: 1042 bytes File creation time: Mon Aug 23 12:34:16 2021 File modification time: Thu Aug 26 15:01:32 2021
Full Code
Here’s the complete code for getting the basic file metadata in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import os import time file_path = "example.txt" # Get the file size file_size = os.path.getsize(file_path) # Get the file creation time file_creation_time = time.ctime(os.path.getctime(file_path)) # Get the file modification time file_modification_time = time.ctime(os.path.getmtime(file_path)) print("File path:", file_path) print("File size:", file_size, "bytes") print("File creation time:", file_creation_time) print("File modification time:", file_modification_time) |
Conclusion
In this tutorial, we have demonstrated how to get basic file metadata in Python using the os and time libraries. This can be a starting point for further exploration, such as investigating more advanced metadata (like file permissions or owner information) or developing automation tasks that rely on file metadata. Happy coding!