How to get the size of a file in Python
In this tutorial, we will be learning how to get the size of a file in Python. The file can be of any extension, .pdf, .py, .txt etc. Today we will be introducing another Python module OS. So without further ado, let’s get started.
Python OS Module
First of all, let’s learn about OS Module provided by Python.
OS module provides a way of using operating system dependent functionality. Its functions allow you to interface with the underlying operating system that Python is running on, be it Mac, Windows or Linux. With this module, information about the location or the process can be founded.
Get size of a file in Python
Since we are now familiar with the Os module, Let’s use it.
First, we need to import OS
We will now use another module provided by OS which is os.path. This module provides different functions that are used for different purposes such as for retrieving path names, merging and normalizing in python. os.path.getsize() is a function which takes path_of_file as a parameter and returns the size of a file in Bytes.
So now let’s use it.
We stored the returned size in Bytes in variable size. Finally, to print the size,
print("Size of the file is: ",size)
Our complete code looks like this.
import os size=os.path.getsize("C:\\Users\\Nitesh\\Desktop\\mongo_project\\basic.py") print("Size of the file is: ",size)
Size of the file is: 105