How to check file size in Python?
Prerequisites:
Given a file, the task here is to generate a Python Script to print its size. This article explains 2 methods to do so.
Approach
- Import module
- Get file size
File in use
Name: Data.csv
Size: 226 bytes
Method1: Using pathlib
Path().stat().st_size() function of pathlib module gets the size of any type of the file and the output of this function will be the size of the file in bytes.
Syntax:
Path('filename').stat().st_size()
Example:
Python3
from pathlib import Path
sz = Path( 'Data.csv' ).stat().st_size
print (sz)
|
Output:
Method 2: With Os module
os.path.getsize() function only works with os Library, with the help of importing this library we can use this to get the size of any type of file and the output of this function will be the size of the file in bytes.
Syntax:
getsize(filename)
Example:
Python3
import os
sz = os.path.getsize( "Data.csv" )
print (sz)
|
Output:
We got the result as 226 bytes
Last Updated :
17 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...