How to Check if a File is Empty in Python?

In this tutorial, I will explain how to check if a file is empty in Python. I recently faced this issue while building a data processing pipeline for a client in New York, where I needed to ensure that the input files were not empty before feeding them into the system. Let us explore different approaches to check if a file is empty using Python, along with practical examples.

Check if a File is Empty in Python

Let us learn how to check if a file is empty in Python.

Read How to Get File Name Without Extension in Python?

1. Use os.path.getsize()

One of the simplest ways to check if a file is empty is by using the os.path.getsize() function from the os module in Python. This function returns the size of the file in bytes. If the file size is 0, it means the file is empty.

Here’s an example:

import os

file_path = 'path/to/your/file.txt'
if os.path.getsize(file_path) == 0:
    print("The file is empty.")
else:
    print("The file is not empty.")

Output:

The file is not empty.

You can see the output in the screenshot below.

Check if a File is Empty in Python

In this example, we provide the path to the file we want to check. If the os.path.getsize() function returns 0, it means the file is empty, and we print a corresponding message. Otherwise, we print that the file is not empty.

Check out How to Write Multiple Lines to a File in Python?

Handle File Not Found Error

It’s important to note that if the file does not exist, the os.path.getsize() function will raise a FileNotFoundError. To handle this case, we can use a try-except block.

import os

file_path = 'path/to/your/file.txt'
try:
    if os.path.getsize(file_path) == 0:
        print("The file is empty.")
    else:
        print("The file is not empty.")
except FileNotFoundError:
    print("The file does not exist.")

Output:

The file does not exist.

You can see the output in the screenshot below.

How to Check if a File is Empty in Python

In this updated example, we wrap the file size check inside a try block. If the file is not found, the FileNotFoundError is caught in the except block, and we print a message indicating that the file does not exist.

Read How to Write Lines to a File in Python?

2. Use os.stat()

Another approach to check if a file is empty is by using the os.stat() function. This function returns a tuple containing various file attributes, including the file size.

import os

file_path = 'path/to/your/file.txt'
if os.stat(file_path).st_size == 0:
    print("The file is empty.")
else:
    print("The file is not empty.")

Output:

The file is not empty.

You can see the output in the screenshot below.

Check if a File is Empty in Python os.stat()

In this example, we use os.stat(file_path).st_size to retrieve the size of the file. If the size is 0, we consider the file to be empty.

Check out How to Clear a File in Python?

Check Empty Files for Different File Formats

So far, we’ve seen examples using plain text files (.txt). However, you may need to check for empty files in different formats such as CSV or XLSX. Let’s explore how to handle these cases.

1. Check Empty CSV Files

To check if a CSV file is empty, we can use the csv module in Python. Here’s an example:

import csv

file_path = 'path/to/your/file.csv'
with open(file_path, 'r') as csv_file:
    reader = csv.reader(csv_file)
    if not next(reader, None):
        print("The CSV file is empty.")
    else:
        print("The CSV file is not empty.")

In this example, we open the CSV file using the open() function in read mode (‘r’). We create a csv.reader object to read the contents of the file. The next(reader, None) statement attempts to read the first row of the CSV file. If there are no rows (i.e., the file is empty), it returns None, and we print a message indicating that the CSV file is empty. Otherwise, we print that the CSV file is not empty.

Read How to Read XML Files in Python?

2. Check Empty XLSX Files

Checking if an XLSX file is empty requires a different approach since XLSX files have a more complex structure compared to plain text or CSV files. We can use the openpyxl library to handle XLSX files.

from openpyxl import load_workbook

file_path = 'path/to/your/file.xlsx'
workbook = load_workbook(file_path)
sheet = workbook.active

if sheet.max_row == 1 and sheet.max_column == 1 and sheet.cell(row=1, column=1).value is None:
    print("The XLSX file is empty.")
else:
    print("The XLSX file is not empty.")

In this example, we use the load_workbook() function from the openpyxl library to load the XLSX file. We retrieve the active sheet using workbook.active. To check if the XLSX file is empty, we verify three conditions:

  1. The maximum number of rows is 1 (sheet.max_row == 1).
  2. The maximum number of columns is 1 (sheet.max_column == 1).
  3. The value of the cell in row 1 and column 1 is None (sheet.cell(row=1, column=1).value is None).

If all three conditions are met, it means the XLSX file is empty, and we print a corresponding message. Otherwise, we consider the file to be non-empty.

Check out How to Skip the First Line in a File in Python?

Conclusion

In this tutorial, I helped you learn how to check if a file is empty in Python. I covered methods such as using os.path.getsize() and os.stat() for general file types, as well as specific techniques for handling CSV and XLSX files.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.