In this context, we will discuss about how to get the size of the file in Python.
There are two approaches to get the file size. which we will discuss further.
First Approach:
In this method, we will get the file size using the OS module.
https://drive.google.com/file/d/1pgmRoyDFucQDRcmmV4xFF6W8sjznc1Co/view?usp=drivesdk
Let me explain the above code-
import os get_size = os.stat("C:\\Users\\akula\\OneDrive\\Desktop\\Trip\\Codes\\file.txt") print("Size Of The File :",get_size.st_size)
- Firstly, we are importing the os module, which provides various functions that help us to interact with the operating system.
- Secondly, we need to declare a variable and assign it to os.stat().
- os.stat() is used for retrieving the status of the file by specifying the path of the file, who’s size is needed.
- Lastly, we will get the file size using the method “variable_name.st_size” in numeric value.
Output:
The result of above code:
https://drive.google.com/file/d/1pvXiv0efYeppDdhhQptFLDy2l-NFzO8F/view?usp=drivesdk
As here we used the “file.txt” to get the size of it and you can see the output as it is showing 11, which is accurate.
https://drive.google.com/file/d/1pjvareRRUxBz536X43RUP9KqF1GrE18i/view?usp=drivesdk
Second Approach:
In this method, we will get the file size using the pathlib module.
https://drive.google.com/file/d/1pzaFA4KB3PS95C4gBw3e8MLCq2xrCNiX/view?usp=drivesdk
Let me explain the above code-
import pathlib file_size = pathlib.Path("C:\\Users\\akula\\OneDrive\\Desktop\\Trip\\Codes\\file.txt") print("Size Of The File: ", file_size.stat().st_size)
- Firstly, we are importing the pathlib module, which is the advanced module. which help’s us to deal with various files, irrespective of the operating system.
- Secondly, we need to declare a variable and assign it to pathlib.path().
- pathlib.path() is a kind of class which is used to specify the path of the file, who’s size is needed.
- At last, we are using the “variable_name.stat().st_size”, which is used to know the status of the code as well as it returns the file size in numeric value.
Output:
The result of above code:
https://drive.google.com/file/d/1q43eQW3BZfS_5t9cvwOiY_mB1td22vc7/view?usp=drivesdk
As we used the same file from the above approach, we got accurate result ,which is 11.