Python Check If File is Empty – 4 Ways

Are you looking for how you can check if the file is empty in Python? In this post, I will show you to check if any given file is empty or not in Python in three different ways.

The best way would be just by checking the size of the file. But there are other various ways using which you can quickly identify if the given file is empty or not. Note that you should know the path of your file in python.

1. Using seek method of OS:

The OS[1] library of python has an inbuilt function that can be used on file objects to verify whether the given file is empty or not. This is the most efficient way to check and it actually tells if the file is empty in any given condition.

import os

with open(r"\user\FileToCheck.txt") as currFile:
  currFile.seek(0, os.SEEK_END) #if it goes to end of the file
  if currFile.tell() == 0:
  	print("File is Empty")
  else:
    print("File is not Empty")

If you think the above code is complicated then you can try out other methods mentioned below examples.

2. Using OS function st_size:

In Python the OS library has an inbuilt function named st_size, this function if used on any file will let you know the size of that file. And if the size of the file is zero it means that the file is empty and there is no content present. Let us see it in actual code.

import os

isFileEmpty = os.stat(r"\user\FileToCheck.txt").st_size
if isFileEmpty == 0:
  print("File is Empty")
else:
  print("File is not Empty")

Output:

Python Check If File is Empty - 4 Ways

3. Using Path Lib inbuilt Function

There is a library present in Python 3 and the above with the name Path which has an inbuilt function as a stat and attributes st_size.

from pathlib import Path

currentPath = Path("user/path/toTheFile/FileToCheck.txt")
isFileEmpty = currentPath.stat()
if isFileEmpty.st_size == 0:
  print("File is Empty")
else:
  print("File is not Empty")

Output:

File is Empty

4. Using getsize function of OS

In the OS library, we have another inbuilt function known as getsize(). This function returns zero if the file or input file is empty otherwise it will return the size of the file.

import os

isFileEmpty = os.path.getsize("user/path/toTheFile/FileToCheck.txt")

if isFileEmpty == 0:
  print("File is Empty")
else:
  print("File is not Empty")

But do note that this function can throw an OS exception in a few cases hence it is always advisable to put this getsize function code line in a try and catch to handle the exception in Python.

Output:

File is not Empty

Wrap Up

That is all for the post in which you learned how to check if the file is empty in 4 ways. Let me know if you find any errors on this page in the comments section I would be happy to update the code and provide you the credit for it.

If you liked our post let us know in the comment section. Please follow us on Facebook and Twitter.

Leave a Comment