How to check file size in Python

Many times while doing file processing python, we need to know file size in bytes/KBs/MBs. You can get file size using multiple methods, following are two simple methods to get file size using os module.

I have run this file for two inputs,one is image and another is empty file.

################################################################################################
# name: file_size.py
# desc: Getting gile size using python
# date: 2019-02-10
# Author: conquistadorjd
################################################################################################
import io, os
print('*** Program Started ***')
image_path_input = '/home/conquistador/code/github/python-01-utilities/file/input/'
image_name_input = 'file_size-01.jpg' #'file_size-02'
if os.stat(image_path_input + image_name_input).st_size ==0 :
print('Input file is empty')
else :
print('Input file is not empty')
print('File size (in Bytes) : ',os.stat(image_path_input + image_name_input).st_size)
print('File size (in Bytes) : ',os.path.getsize (image_path_input+image_name_input))
image_name_input = 'file_size-02'
if os.stat(image_path_input + image_name_input).st_size ==0 :
print('Input file is empty')
else :
print('Input file is not empty')
print('File size (in Bytes) : ',os.stat(image_path_input + image_name_input).st_size)
print('File size (in Bytes) : ',os.path.getsize (image_path_input+image_name_input))
print('*** Program Ended ***')

view raw
file_size.py
hosted with ❤ by GitHub

Here is the output of the program

$ python3.6 file_size.py 
*** Program Started ***
Input file is not empty
File size (in Bytes) : 147162
File size (in Bytes) : 147162
Input file is empty
File size (in Bytes) : 0
File size (in Bytes) : 0
*** Program Ended ***

Actual file size

I have added a check to see if file size is empty, you might need to check file size before doing any processing on files.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.