How To Get Metadata Of A File In Python

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:

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:

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:

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:

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!