Append CSV files with matching headers using Python
Appends first.csv then second.csv with one header, preserving cell text and parsed record order. It refuses to overwrite merged.csv.
Before you start
- Python 3.10 or later. Run in a working folder with a backup of your source; output files may be replaced unless opened in exclusive mode.
- Place first.csv and second.csv in that folder. Examples use UTF-8, a comma delimiter and a header row. Column-specific recipes use id,label,amount,status,note; adapt names to your file.
python3 - <<'PY'
import csv
paths = ["first.csv", "second.csv"]
with open("merged.csv", "x", encoding="utf-8", newline="") as target:
writer = csv.writer(target)
headers = None
for path in paths:
with open(path, encoding="utf-8-sig", newline="") as source:
reader = csv.reader(source, strict=True)
current = next(reader, None)
if current is None:
raise ValueError(f"{path}: missing header")
if headers is None:
headers = current
writer.writerow(headers)
if current != headers:
raise ValueError(f"{path}: header names/order differ")
for row in reader:
if len(row) != len(headers):
raise ValueError(f"{path}: wrong field count")
writer.writerow(row)
print("Wrote merged.csv")
PYLimits and output
- CSV has no stored type schema. Python keeps fields as strings until an example explicitly converts a value. These recipes do not add spreadsheet formula protection; import sensitive-looking strings as text in spreadsheets.
- This is strict append, not a key join or header union. A late validation error may leave a partial merged.csv; remove it before retrying after fixing the source.
Documentation: Python CSV reader and writer