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"
with open(file_path, "w") as f:
pass
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.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")
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).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.
with open("whitespace.txt", "w") as f:
f.write("\n")
import os
print(f"Size: {os.path.getsize('whitespace.txt')} bytes")
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:
if os.path.getsize(non_existent_file) == 0:
print("Empty")
except OSError as e:
print(f"Error: {e}")
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.Conclusion
To check if a file is empty in Python:
- Use
os.path.getsize(path) == 0for a fast, standard metadata check. - Use
Path(path).stat().st_size == 0if you are using modernpathlibsyntax. - Read and
.strip()the content if you need to ignore whitespace (spaces/newlines).