You can split a CSV into multiple files with Python's built-in csv module in a few lines: read the header, then write groups of rows to separate files using either a fixed row count per file or a value in a column. No third-party packages are required for the basic approach; pandas is optional if you prefer a one-liner. The steps below cover both methods, plus the mistakes that most often produce broken output.
What You'll Need
- Python 3 installed (the
csvmodule ships with it). - A CSV file you have permission to read and write, and a folder for the output files.
- Optional: pandas installed from the official PyPI package if you want the shortcut method.
- A text editor or IDE. Labels in editors differ by version, so the exact menu names may vary.
Step-by-Step
- Inspect the CSV first. Open it in a spreadsheet or text editor and confirm the delimiter (comma, semicolon or tab), whether the first row is a header, and whether any fields contain commas inside quotes. The
csvmodule handles quoted commas correctly; naive string splitting does not. - Decide the split rule. Two common rules: a fixed number of data rows per output file (for example 1,000 rows each), or one file per unique value in a column such as
regionorcategory. Pick one before writing code. - Set up the script. Create a file such as
split_csv.pyin the same folder as your CSV, or use an absolute path. Keep input and output in separate folders so you do not overwrite the source. - Open the source with the correct encoding. Use
open('input.csv', newline='', encoding='utf-8'). Thenewline=''argument is required by thecsvmodule; omitting it can produce blank lines between rows on Windows. If the file came from Excel on Windows,utf-8-sigoften reads it more reliably. - Read the header row. Call
reader = csv.reader(f)thenheader = next(reader). If the file has no header, skip this and treat the first row as data. - Write the fixed-size split. Loop over the reader, collect rows into a list, and every time the list reaches your chunk size, open a new file named like
part_1.csv, write the header withwriter.writerow(header), write the buffered rows, and clear the list. After the loop, write any remaining rows to a final file. Always write the header to every output file so each one opens cleanly in a spreadsheet. - Write the column-based split. Build a dictionary keyed by the column value. For each row, append it to the matching list. Then loop over the dictionary and write one file per key, again writing the header first. Sanitise the key before using it as a filename: strip characters like
/ \ : * ? " < > |and replace spaces with underscores, or the write will fail on Windows. - Close files properly. Use
with open(...) as out:blocks so each file closes even if an error occurs. If you open files manually, callclose()on every one. - Verify the output. Count rows in the source and in all output files combined; the totals should match. Open two or three output files and check that the header and a few data rows look correct.
- Optional pandas shortcut. If pandas is installed,
df = pd.read_csv('input.csv')thendf.iloc[i:i+1000].to_csv(f'part_{n}.csv', index=False)inside a loop does the fixed-size split in fewer lines. For a column split, group by the column and write each group withto_csv. pandas is a third-party package, so install it only from PyPI withpip install pandas.
Common Mistakes
- Forgetting
newline='', which adds blank lines between rows on Windows. - Using
split(',')on each line instead of thecsvmodule, which breaks on quoted fields containing commas. - Writing the header only to the first output file, leaving the rest without column names.
- Using raw column values as filenames when they contain slashes, colons or question marks.
- Overwriting the source file by writing output into the same folder with the same name pattern.
- Reading with the wrong encoding, which turns accented characters into garbled text.
Tips
- Name output files with zero-padded numbers (
part_01.csv,part_02.csv) so they sort correctly. - Add a
max_rowsorchunk_sizevariable at the top of the script rather than hard-coding numbers in the loop. - For very large files, process row by row instead of loading everything into memory; the fixed-size method above already does this.
- Log the filename and row count for each output file so you have a record of what was written.
- Keep a copy of the original CSV until you have verified the split.
Troubleshooting
- Blank lines between rows: add
newline=''to theopen()call for both reading and writing. - Garbled characters: try
encoding='utf-8-sig'or the encoding your source system uses, such aslatin-1. - Wrong number of columns per row: the delimiter is probably not a comma. Pass
delimiter=';'ordelimiter='\t'tocsv.reader. - Permission or file-in-use error: close the file in Excel or your editor, and check that the output folder is writable.
- Filename error on Windows: sanitise the column value before using it as a name; Windows forbids several characters.
- Row counts do not add up: check whether the header is being counted as a data row, and whether the final partial chunk was written.
- If that did not work: print the first five rows and the detected header to the console, compare them with the file, and simplify the script to one method before adding features back.
Frequently Asked Questions
Can I split a CSV without installing anything?
Yes. The built-in csv module is part of standard Python and is enough for both fixed-size and column-based splits.
How do I keep the header in every output file?
Read the header once with next(reader), store it, and call writer.writerow(header) immediately after opening each new output file.
Can I split by a column value instead of row count?
Yes. Group rows into a dictionary keyed by that column, then write one file per key. Sanitise the key before using it as a filename.
Does this work on Windows and macOS?
Yes, with one difference: always pass newline='' when opening files, which prevents extra blank lines on Windows. Filename rules are also stricter on Windows.
What if my file is too large to fit in memory?
Use the fixed-size method, which reads and writes one row at a time. Avoid loading the whole file into a list or a pandas DataFrame.
Can I split an Excel file the same way?
Not with the csv module. Save the sheet as CSV first, or use a library that reads Excel files, such as openpyxl from PyPI.