Skip to main content

How to Check If a File Is Empty in Python

When working with file I/O in Python, it is often necessary to verify if a file contains data before attempting to process it. Attempting to parse an empty JSON file or iterate over empty lines can lead to runtime errors or unexpected behavior.

This guide explains how to check if a file is empty using the traditional os module, the modern pathlib module, and how to handle files that contain only whitespace.

Method 1: Using os.path.getsize (Standard Approach)

The most efficient way to check for an empty file (without opening it) is to inspect its metadata size in bytes. If the size is 0, the file is empty.

import os

file_path = "my_data.txt"

# Create a dummy empty file for this example
with open(file_path, "w") as f:
pass

# ✅ Check file size
if os.path.getsize(file_path) == 0:
print(f"The file '{file_path}' is empty.")
else:
print(f"The file '{file_path}' contains data.")

Output:

The file 'my_data.txt' is empty.
note

os.path.getsize() returns the size in bytes. This method is fast because it reads filesystem metadata rather than the file contents.

Method 2: Using pathlib (Modern Approach)

Introduced in Python 3.4, the pathlib module offers an object-oriented interface to the filesystem. This is generally preferred for modern Python scripts.

from pathlib import Path

file_path = Path("my_data.txt")

# ✅ Check size using stat()
if file_path.stat().st_size == 0:
print("File is empty (checked via pathlib).")
else:
print("File has content.")

Output:

File is empty (checked via pathlib).
tip

You can also verify the file exists before checking size using if file_path.exists() and file_path.stat().st_size == 0:.

Method 3: Checking for Logical Emptiness (Whitespace)

A file might contain spaces, tabs, or newlines (\n). Technically, its size is greater than 0 bytes, but logically, it contains no data. To check for this, you must read the content.

# Create a file with only a newline
with open("whitespace.txt", "w") as f:
f.write("\n")

# ⛔️ Incorrect: getsize returns 1 byte (the newline character)
import os
print(f"Size: {os.path.getsize('whitespace.txt')} bytes")

# ✅ Correct: Read and strip whitespace
with open("whitespace.txt", "r") as f:
content = f.read()
if len(content.strip()) == 0:
print("File is logically empty (contains only whitespace).")

Output:

Size: 1 bytes
File is logically empty (contains only whitespace).

Common Pitfalls: FileNotFoundError

Both os.path.getsize() and pathlib will raise an error if the file does not exist. You should wrap your check in a try-except block or verify existence first.

import os

non_existent_file = "ghost_file.txt"

try:
# ⛔️ This raises an error if file is missing
if os.path.getsize(non_existent_file) == 0:
print("Empty")
except OSError as e:
print(f"Error: {e}")

# ✅ Safe approach
if os.path.exists(non_existent_file) and os.path.getsize(non_existent_file) == 0:
print("File exists and is empty.")
else:
print("File does not exist or is not empty.")

Output:

Error: [Errno 2] No such file or directory: 'ghost_file.txt'
File does not exist or is not empty.
warning

Be aware of Race Conditions. If you check os.path.exists() and then immediately call os.path.getsize(), it is theoretically possible for the file to be deleted in the split second between those two commands.

Conclusion

To check if a file is empty in Python:

  1. Use os.path.getsize(path) == 0 for a fast, standard metadata check.
  2. Use Path(path).stat().st_size == 0 if you are using modern pathlib syntax.
  3. Read and .strip() the content if you need to ignore whitespace (spaces/newlines).