Sub topic 13
Reading files back to verify them
A file that wrote without an error can still hold the wrong data. A CSV can drop leading zeros. An Excel sheet can store a date as text. A Parquet dataset can reorder columns. This chapter shows how to read each file back and compare it with the original. It assumes you can already write CSV, Excel, and Parquet files with to_csv, to_excel, and to_parquet. It also assumes you know the basic dtypes (int, float, string, datetime). The examples assume pandas 2.x, plus openpyxl for Excel and pyarrow for Parquet.
What "verified" means
Verification means reading the file back with the same code a downstream user would run, then checking that the result matches what you meant to save. Checks come in layers, from cheap to strict:
- The file exists and is not empty.
- The row and column counts match.
- The dtypes match.
- Every value matches.
Layers 2 to 4 are what a read-back gives you. Layer 4 is the strictest, and pd.testing.assert_frame_equal performs it.
Comparing with assert_frame_equal
assert_frame_equal(left, right) returns None when the frames match. When they differ, it raises an AssertionError that says what differs: values, dtypes, index, or column names. That makes it better than left.equals(right), which only returns True or False.
A small wrapper keeps the checks readable:
import pandas as pd
def verify(original, restored, **kwargs):
try:
pd.testing.assert_frame_equal(original, restored, **kwargs)
except AssertionError as err:
print("MISMATCH:", err)
return False
print("OK")
return TrueUse it with a Parquet round trip. Parquet stores dtypes, so no extra arguments are needed:
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", None],
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_parquet("orders.parquet", index=False)
restored = pd.read_parquet("orders.parquet")
verify(df, restored)Missing values do not cause a mismatch here. assert_frame_equal treats NaN in the same position on both sides as equal.
Arguments that loosen or tighten the check
The defaults are strict. Relax only what you have a reason to relax.
| Argument | Default | Use it when |
|---|---|---|
| `check_dtype` | `True` | You accept a different but equivalent dtype, such as `int32` against `int64`. |
| `check_exact` | `False` for floats | Set it to `True` to demand bit-identical floats. |
| `rtol`, `atol` | `1e-5`, `1e-8` | You wrote floats with `float_format` and expect rounding. |
| `check_like` | `False` | Row and column order may differ, but labels must match. |
| `check_index_type` | `"equiv"` | The index type is not part of what you are testing. |
| `check_names` | `True` | Index and column `name` attributes may differ. |
Prefer a tolerance over check_dtype=False. A tolerance only forgives rounding. check_dtype=False can hide a real type change.
Verifying a CSV round trip
CSV stores text, so a bare read_csv guesses the types. Write a file where those guesses go wrong:
orders = pd.DataFrame({
"order_id": [1, 2, 3],
"zip_code": ["01234", "20500", "98101"],
"amount": [19.99, 5.5, 7.25],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
orders.to_csv("orders_check.csv", index=False)
naive = pd.read_csv("orders_check.csv")
print(naive.dtypes)
verify(orders, naive)The printed dtypes show two problems. zip_code was read as int64, so "01234" became 1234. ordered_at is object, which means plain strings. The check fails and the message points at the first differing column.
Now repeat the read with the arguments a careful reader would use:
restored = pd.read_csv(
"orders_check.csv",
dtype={"zip_code": str},
parse_dates=["ordered_at"],
)
verify(orders, restored)The comparison now passes. The failing check showed that the file is fine, but readers need dtype and parse_dates to read it correctly. If you publish a CSV, document those arguments.
Index columns
If you forget index=False when writing, the index becomes an extra first column. Reading it back gives an Unnamed: 0 column and a fresh RangeIndex. Fix this at write time, or read with index_col=0. The check catches both cases as a column mismatch.
Rounded floats
With float_format="%.2f", the file holds rounded text, so exact equality fails whenever the original had more than two decimals. Compare with a tolerance that matches the rounding:
precise = pd.DataFrame({"amount": [19.987, 5.5, 7.254]})
precise.to_csv("amounts.csv", index=False, float_format="%.2f")
restored = pd.read_csv("amounts.csv")
verify(precise, restored, atol=0.005, rtol=0)Setting rtol=0 makes the check absolute, so the allowed error is half a cent on every value.
Verifying an Excel workbook
read_excel returns the first sheet by default. To check a whole workbook, pass sheet_name=None. That returns a dictionary that maps each sheet name to a DataFrame:
summary = df.groupby("customer", dropna=True)["amount"].sum().to_frame()
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="orders", index=False)
summary.to_excel(writer, sheet_name="summary")
sheets = pd.read_excel("report.xlsx", sheet_name=None)
print(list(sheets))
verify(df, sheets["orders"])
verify(summary, sheets["summary"].set_index("customer"))The summary sheet was written with its index, so it comes back as a regular column named customer. The set_index call restores it. Passing index_col=0 to read_excel does the same thing.
Excel has its own risks:
- Numbers and dates come back typed, but a column that mixes numbers and text stays
object. - Empty cells come back as
NaN. - Integer columns that contain empty cells come back as
float64. - Dates written as text strings do not become datetimes. Check
dtypesafter reading.
If a column mismatches, print sheets["orders"].dtypes and compare it by eye with df.dtypes. The cause is usually one of these four.
Verifying Parquet, including partitioned datasets
Parquet keeps dtypes, so most failures come from the index and from partitioning.
- Index. By default,
to_parquetstores aRangeIndexas light metadata and writes any other index as a column. If you wrote withindex=Falseand the original has a filtered index like[0, 2, 5], compare againstdf.reset_index(drop=True). - Partitioned datasets.
partition_colsmoves the column into directory names. On read, the column comes back at the end of the frame, typically as acategory, and row order is not guaranteed.
sales = pd.DataFrame({
"country": ["DE", "DE", "FR"],
"amount": [10.0, 12.5, 8.0],
})
sales.to_parquet(
"sales_parquet",
engine="pyarrow",
compression="zstd",
partition_cols=["country"],
)
back = pd.read_parquet("sales_parquet")
print(back.dtypes)
expected = sales.assign(country=sales["country"].astype("category"))
verify(
expected.sort_values(["country", "amount"]).reset_index(drop=True),
back.sort_values(["country", "amount"]).reset_index(drop=True),
check_like=True,
)Sorting both sides on the same keys removes row order from the comparison. check_like=True ignores the moved column. Converting country to category on the expected side reflects the way the dataset is read, not a defect in the write.
You can also inspect a Parquet file without loading its data. The footer holds the row count and the schema:
import pyarrow.parquet as pq
meta = pq.ParquetFile("orders.parquet")
print(meta.metadata.num_rows)
print(meta.schema_arrow)This is a cheap check for files too large to load.
Verifying chunked output
A CSV you built in chunks might be too big to load whole. In that case, compare row counts by streaming both files, and avoid a full comparison:
def count_rows(path, chunksize=100_000):
return sum(len(chunk) for chunk in pd.read_csv(path, chunksize=chunksize))
assert count_rows("input.csv") == count_rows("output.csv")The most common chunking bug is a repeated header row. Each later chunk writes its own header line if you forget header=(i == 0). Those header lines then show up as data rows, and the row count is higher than expected. A cheap extra check is to sum one numeric column in both files with the same chunked pattern and compare the totals.
Common mistakes
- Comparing a file against a DataFrame that has not been through the same transformations. Rebuild the expected frame explicitly. Do not reuse a variable you have modified since writing.
- Verifying with
check_dtype=Falsefrom the start. You lose the information that tells you which read argument is missing. - Checking only
shape. A file can have the right shape and wrong values, such as lost leading zeros. - Reading the file with different arguments than your consumers use. Verify with the exact reader call that you will document or ship.
Exercise
You write a DataFrame with a text column sku containing values like "007" using df.to_csv("items.csv", index=False). You read it back with pd.read_csv("items.csv") and assert_frame_equal fails. What is the likely cause, and what do you change in the read call?
Show answer
read_csv infers sku as an integer, so "007" becomes 7. The file is correct. Read it with pd.read_csv("items.csv", dtype={"sku": str}), then compare again.
Exercise
You wrote sales.to_parquet("sales_parquet", partition_cols=["country"]) and compare pd.read_parquet("sales_parquet") with sales. The comparison fails even though no data was lost. Name two differences you should account for.
Show answer
The country column moves to the end of the frame and comes back as a category dtype. Row order is also not guaranteed. Convert country to category on the expected frame, sort both sides on the same keys, reset their indexes, and pass check_like=True.
Exercise
A CSV was written with float_format="%.1f" from values like 3.14159. Which two assert_frame_equal arguments let you verify the file against the original, and what values would you choose?
Show answer
Use atol and rtol. Set rtol=0 and atol=0.05, because one decimal place rounds with an error of at most 0.05.