This post will discuss how to determine whether a file is empty in Python.

You can easily check for an empty file in Python by finding the size of the file, which should be 0 bytes. There are several ways to do that:

1. Using os module

The os.stat() function returns a stat_result object, whose st_size attribute stores the size of the file, in bytes.

Download Code

 
Alternatively, you can use the os.path.getsize() function to get the specified file size in bytes.

Download Code

2. Using pathlib module

With Python 3.4, you can use the pathlib.Path.stat() function, which returns the stat_result object containing information about the specified path, similar to the os.stat() function.

Download Code

3. Using File object

Another option is to open the file in reading mode using the built-in function open() and set the current position of the file descriptor at the end with the seek() function. Then you can use the tell() function to get the current position of the cursor in bytes.

Download Code

That’s all about determining whether a file is empty in Python.