How to get Details of a File using Python

Updated onbyAlan Morel
How to get Details of a File using Python

Because Python is a server-side language, it can access and manipulate the file system just like any other language.

That means that you can use Python to get information about files, such as their size, creation date, and more.

In this post, we'll learn how you can use Python to get details of a file on your file system.

Import the os module

To get file details in Python, you can use the os module.

The os module provides a number of functions for interacting with the file system.

First, import the os module:

PYTHON
import os

Get the file size

Now that you've imported the os module, you can use the os.path.getsize() function to get the size of a file.

First define a file path to the file you want to get the size of, and keep in mind that the path will be different depending on your operating system.

PYTHON
file_path = "/Users/sabe/text.txt" # Mac or Linux file_path = "C:\\Users\\sabe\\text.txt" # Windows

Then use the os.path.getsize() function to get the size of the file:

PYTHON
import os file_path = "/Users/sabe/text.txt" file_size = os.path.getsize(file_path) print(file_size)

This will return the size of the file in bytes.

Get the file creation date

To get the creation date of a file, you can use the os.path.getctime() function.

PYTHON
import os file_path = "/Users/sabe/text.txt" file_creation_date = os.path.getctime(file_path) print(file_creation_date)

This returns the number of seconds since the epoch, which is January 1, 1970.

Get the file modification date

To get the modification date of a file, you can use the os.path.getmtime() function.

PYTHON
import os file_path = "/Users/sabe/text.txt" file_modification_date = os.path.getmtime(file_path) print(file_modification_date)

Likewise, this returns the number of seconds since the epoch.

How to get the stats of a file

Another thing you can fetch about a file is its stats.

The os.stat() function returns a stat_result object that contains a number of attributes about the file.

PYTHON
import os file_path = "/Users/sabe/text.txt" file_stats = os.stat(file_path) print(file_stats)

These attributes include the file size, file owner id, file group id, permissions, and more.

Conclusion

In this post, we learned how to get file details in Python.

This included getting the size of a file, the creation date, the modification date, and the stats of a file.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.