Split CSV at parsed record boundaries with Python
Creates part-001.csv and following parts with at most 1,000 data records each and a repeated header. Quoted multiline fields are never split across files.
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 input.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
from itertools import islice
records_per_file = 1000
with open("input.csv", encoding="utf-8-sig", newline="") as source:
reader = csv.reader(source, strict=True)
headers = next(reader, None)
if headers is None:
raise ValueError("Expected a header")
part = 0
while batch := list(islice(reader, records_per_file)):
if any(len(row) != len(headers) for row in batch):
raise ValueError("A record has the wrong field count")
part += 1
with open(f"part-{part:03}.csv", "x", encoding="utf-8", newline="") as target:
writer = csv.writer(target)
writer.writerow(headers)
writer.writerows(batch)
print(f"Wrote {part} parts")
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 recipe splits by record count, not byte size. It refuses to overwrite existing parts; a later malformed record can leave earlier parts on disk.
Documentation: Python CSV reader and writer