HOWTO · Python
How to Check if File Is Empty in Python
We will learn how to check whether files are empty or not. We also have a look at different issues that were raised while checking an empty file in Python.
On this page
A zero-byte file contains no bytes, but “empty” can mean something different for structured data: a CSV may parse to no rows, and an Excel workbook may contain formatting or sheet metadata even when a sheet has no records. Choose the check that matches what you need to know. A file-size check answers whether a regular file has bytes; a table check answers whether a parsed table has rows.
Check Whether a File Is Empty by Its Size
A filesystem reports size in bytes. For a regular file, a size of 0 means it has no bytes. A nonzero size does not prove that a text file contains meaningful content: it could contain only whitespace, a byte-order mark, or other data your application does not use. If you mean “no non-whitespace text,” read and test the decoded contents instead.
This sample makes its own input in a temporary folder and removes it when the block ends. It uses only the Python standard library, so you can paste it into a script without preparing a separate data file or changing a machine-specific location. The checks return Boolean values that your program can use in a conditional or pass to a logging function. Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "notes.txt"
path.write_text("Ready to process.\n", encoding="utf-8")
print(path.is_file())
print(path.stat().st_size == 0)
The temporary directory makes the example independent of a particular computer’s folders. The first check verifies that the path is a regular file, and the second tests whether its byte size is zero.
Use pathlib to Check a File
Use Path.is_file() before asking for a file’s size. It returns False when the path is missing or is not a regular file. In a real application, replace path with the path you receive as input; use a raw string for Windows paths if backslashes would otherwise be interpreted as escapes.
from pathlib import Path
path = Path("notes.txt")
if not path.is_file():
print("The path is missing or is not a regular file.")
else:
try:
empty = path.stat().st_size == 0
except OSError as error:
print(f"Could not check the file: {error}")
else:
print(f"Empty: {empty}")
The size lookup is inside the try because the file can disappear or become inaccessible after is_file() succeeds. If stat() fails, the example reports that filesystem error instead of treating it as an empty file. For a one-off check, Path.stat().st_size == 0 is the direct size test; os.path.getsize(path) == 0 is an equivalent alternative that accepts path-like objects.
Check Whether a CSV File Has Rows
CSV files are parsed text, so file bytes are not a reliable count of records. A file with a header but no data rows has bytes while containing no records. Conversely, a CSV that contains only blank lines may not produce a usable table. With pandas, DataFrame.empty is true if either axis has length zero; it does not mean that every cell is blank. Install pandas to use this approach.
The following self-contained example creates a small CSV before parsing it. pandas.read_csv() can raise pandas.errors.EmptyDataError when there are no columns to parse. Catch that specific condition separately from a missing file, permission problem, or malformed CSV, each of which calls for a different response.
from pathlib import Path
from tempfile import TemporaryDirectory
try:
import pandas as pd
except ImportError:
print("Install pandas to run this example.")
else:
with TemporaryDirectory() as folder:
path = Path(folder) / "records.csv"
path.write_text("name\nAda\n", encoding="utf-8")
try:
table = pd.read_csv(path)
except pd.errors.EmptyDataError:
print("The CSV has no parseable columns.")
else:
print(table.empty)
Check Whether an Excel Sheet Has Rows
An .xlsx file contains workbook structure as well as cell values, so its byte size cannot tell you whether a particular sheet has records. Read the sheet and check the resulting DataFrame. read_excel() uses the first sheet by default; pass sheet_name when the data is elsewhere. Reading Excel requires pandas and a compatible Excel engine, such as openpyxl for many .xlsx files.
Adapt the path and sheet name to the workbook you receive. DataFrame.empty checks whether there are rows or columns; a row containing blank cells still counts as a row. If the workbook has no usable rows but includes headings, the table may have columns and zero rows, which is the usual case this check is intended to identify. The existence check below gives a clear message for a workbook already missing; the file can also disappear before read_excel() opens it, so that read handles FileNotFoundError separately.
from pathlib import Path
try:
import pandas as pd
except ImportError:
print("Install pandas and an Excel engine to read a workbook.")
else:
workbook = Path("data.xlsx")
if not workbook.is_file():
print("Provide the path to an existing workbook.")
else:
try:
table = pd.read_excel(workbook, sheet_name="Sheet1")
except FileNotFoundError:
print("The workbook disappeared before it could be read.")
except PermissionError:
print("Permission denied while reading the workbook.")
except (ImportError, ValueError) as error:
print(f"Could not read the selected sheet or Excel engine: {error}")
else:
print(table.empty)
Handle Missing Files and Read Errors
Do not use a broad except: clause to label every failed read as an empty file. A missing path, denied access, malformed input, and a valid file with no rows are different outcomes. For plain files, check is_file() and catch OSError around stat() if the path can change or the process may lack access. For pandas, catch EmptyDataError when handling a CSV with no parseable columns, then handle FileNotFoundError, PermissionError, and parser or engine errors according to your application’s needs. Keep unexpected errors visible during development rather than silently treating them as empty data.
The key distinction is what you are measuring: use the filesystem for bytes, and parse CSV or Excel data when the question is whether a table or sheet has rows. Neither a nonzero size nor an all-blank row should be mistaken for proof that useful records exist; define “usable” according to the application that consumes the file.