Related Articles

Related Articles

How to get file size in Python?
  • Last Updated : 16 Nov, 2020

We can follow different approaches to get the file size in Python. It’s important to get the file size in Python to monitor file size or in case of ordering files in directory according to file size. 

Method 1: Using getsize function of os.path module

This function takes a file path as argument and it returns the file size (bytes). 

Example:

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

# approach 1
# using getsize function os.path module
import os
  
file_size = os.path.getsize('d:/file.jpg')
print("File Size is :", file_size, "bytes")

chevron_right


Output:

File Size is : 218 bytes

Method 2: Using stat function of the OS module

This function takes a file path as argument (string or file object) and returns statistical details about file path given as input. 

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# approach 2
# using stat function of os module
import os
  
file_size = os.stat('d:/file.jpg')
print("Size of file :", file_size.st_size, "bytes")

chevron_right


Output:

Size of file : 218 bytes

Method 3: Using File Object

To get the file size, follow these steps –

  1. Use open function to open the file and store the returned object in a variable.  When the file is opened, cursor points to the beginning of the file.             
  2. File object has seek method use to set the cursor to the desired location. It accepts 2 arguments – start location and end location. To set the cursor at the end location of the file use method os.SEEK_END.
  3. File object has tell method that can be used to get the current cursor location which will be equivalent to the number of bytes cursor has moved. So this method actually returns the size of the file in bytes.

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# approach 3
# using file object
  
# open file 
file = open('d:/file.jpg')
  
# get the cursor positioned at end
file.seek(0, os.SEEK_END)
  
# get the current position of cursor 
# this will be equivalent to size of file
print("Size of file is :", file.tell(), "bytes")

chevron_right


Output:

Size of file is : 218 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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :