How to get Details of a File using Python
Table of Contents
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:
PYTHONimport 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.
PYTHONfile_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:
PYTHONimport 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.
PYTHONimport 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.
PYTHONimport 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.
PYTHONimport 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!
- Getting Started with Express
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js