Skip to content
Related Articles

Related Articles

Improve Article

How to check file size in Python?

  • Difficulty Level : Medium
  • Last Updated : 17 Dec, 2020

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :