Locate all matching CSV files using Path("data_dir").glob("*.csv") (or glob.glob("data_dir/*.csv")), read each file inside a list comprehension or generator expression with pd.read_csv(f), and combine them in a single pass via pd.concat((pd.read_csv(f) for f in files), ignore_index=True)—passing ignore_index=True so the resulting DataFrame receives a clean, continuous 0..N-1 index instead of duplicate row indices from each individual file.
Basic Example
from pathlib import Path
import pandas as pd
# 1. Recommended: Find all CSVs in a directory (sorted for deterministic row order) and concat
csv_files = sorted(Path("sales_data").glob("*.csv"))
df = pd.concat(
(pd.read_csv(file_path) for file_path in csv_files),
ignore_index=True, # Resets index to 0, 1, ..., N-1 instead of repeating 0..M per file
)
print(df.shape)
# 2. Retaining the source filename as a tracking column (`source_file`):
df_with_source = pd.concat(
(pd.read_csv(f).assign(source_file=f.name) for f in csv_files),
ignore_index=True,
)
Key Details & Edge Cases
- Never call
pd.concatordf.appendinside aforloop ($O(N^2)$ memory copies):- Calling
df = pd.concat([df, chunk])inside a loop reallocates and copies the entire growing DataFrame on every file. Collecting all DataFrames in a list/generator and callingpd.concat(..., ignore_index=True)once allocates memory in a single $O(N)$ pass.
- Calling
- Guard against empty file lists (
ValueError: No objects to concatenate):- If
glob("*.csv")finds zero files,pd.concat([])raisesValueError: No objects to concatenate. Validate beforehand (if not csv_files: raise FileNotFoundError("No CSV files found")) or return an empty DataFrame (pd.DataFrame()).
- If
- Recursive subdirectories (
rglob("*.csv")):- To combine CSV files nested across subfolders (e.g.,
2026/01/*.csv,2026/02/*.csv), replace.glob("*.csv")withPath("sales_data").rglob("*.csv").
- To combine CSV files nested across subfolders (e.g.,
- Mismatched column names or missing columns across files:
- By default,
pd.concat(..., join="outer")aligns columns by name (not position) and fills missing columns in older/newer CSVs withNaN. Passjoin="inner"if you only want columns shared across every CSV file, or passusecols=[...]insidepd.read_csv(f, usecols=[...])to load only required columns and slash RAM usage.
- By default,
- Skipping empty 0-byte CSV files (
pd.errors.EmptyDataError):- A single empty 0-byte CSV in a directory causes
pd.read_csv()to abort the entire batch withEmptyDataError: No columns to parse from file. Filter out empty files beforehand using[f for f in csv_files if f.stat().st_size > 0].
- A single empty 0-byte CSV in a directory causes
- Scaling to tens of gigabytes (
pyarrow/polars/duckdb):- When combined CSVs exceed available RAM, use
polars.scan_csv("sales_data/*.csv").collect()orduckdb.sql("SELECT * FROM 'sales_data/*.csv'").df()to stream and filter files multi-threaded in C++/Rust before materializing in memory.
- When combined CSVs exceed available RAM, use
Comparison of Multi-CSV Loading Approaches in Python
| Approach | Memory Efficiency | Preserves Source Filename? | Handles Mismatched Columns? | Best Used When |
|---|---|---|---|---|
pd.concat((pd.read_csv(f) for f in sorted(Path(...).glob("*.csv"))), ignore_index=True) (Recommended) |
Good ($O(N)$ single allocation) | Optional (via .assign(source=f.name)) |
Yes (join="outer" aligns by header name) |
Standard datasets (dozens to thousands of CSVs) fitting comfortably in RAM. |
pd.concat(..., keys=[f.stem for f in files]).reset_index(level=0) |
Good ($O(N)$) | Yes (adds file identifier automatically) | Yes | Tagging every row with its origin file key without mutating each chunk manually. |
polars.scan_csv("dir/*.csv").collect().to_pandas() |
High (multi-threaded lazy streaming) | Yes (include_file_paths="source") |
Yes (how="diagonal_relaxed") |
Large multi-GB CSV datasets where Pandas read_csv is too slow or RAM-heavy. |
duckdb.sql("SELECT *, filename FROM read_csv('dir/*.csv', filename=true)").df() |
High (out-of-core SQL engine) | Yes (filename=true built-in) |
Yes (union_by_name=true) |
Filtering, aggregating, or joining large collections of CSVs via SQL before loading into Pandas. |
You must log in or register to comment.
