Yes, you can split a CSV file with Python using the built-in csv module or pandas, and the most direct way is to read the file line by line and write rows into separate output files based on a condition like row count, a column value, or a header group. Below are six working methods with code examples, plus guidance on choosing the right one for your file size and use case.
Why Split a CSV at All
CSV files grow quickly when they come from exports, logs, or sensor data. A single file with hundreds of thousands of rows can slow down Excel, hit email attachment limits, or break an import tool that expects a maximum row count. Splitting a CSV into smaller chunks makes it easier to open, process in parallel, or upload to systems with size caps. There is also a common need to separate data by a category—for example, splitting a sales file into one CSV per region or per month.
Method 1: Split by Number of Rows (Chunking)
This is the most common request: “split my 1,000,000-row file into files of 100,000 rows each.” The csv module handles this cleanly without loading the entire file into memory. The example below assumes your file is named large.csv and has a header row that you want in every output file.
import csv
chunk_size = 100000
with open('large.csv', 'r', newline='', encoding='utf-8') as infile:
reader = csv.reader(infile)
header = next(reader)
file_number = 1
rows = []
for row in reader:
rows.append(row)
if len(rows) == chunk_size:
with open(f'chunk_{file_number}.csv', 'w', newline='', encoding='utf-8') as outfile:
writer = csv.writer(outfile)
writer.writerow(header)
writer.writerows(rows)
file_number += 1
rows = []
if rows: # write remaining rows
with open(f'chunk_{file_number}.csv', 'w', newline='', encoding='utf-8') as outfile:
writer = csv.writer(outfile)
writer.writerow(header)
writer.writerows(rows)
This works for any file size because it reads one row at a time. If your CSV uses a different delimiter (like a semicolon), pass delimiter=';' to both csv.reader and csv.writer.
Method 2: Split by a Column Value (Grouping)
If you need one file per unique value in a specific column—say, country in column 3—read the file, group rows by that column, and write each group to its own file. The csv module version is memory-friendly for moderately sized files:
import csv
from collections import defaultdict
column_index = 2 # zero-based, so column 3
with open('data.csv', 'r', newline='', encoding='utf-8') as infile:
reader = csv.reader(infile)
header = next(reader)
groups = defaultdict(list)
for row in reader:
groups[row[column_index]].append(row)
for key, rows in groups.items():
safe_key = str(key).replace(' ', '_').replace('/', '_')
with open(f'output_{safe_key}.csv', 'w', newline='', encoding='utf-8') as outfile:
writer = csv.writer(outfile)
writer.writerow(header)
writer.writerows(rows)
This keeps all rows in memory, so for a 10 GB file you would run out of RAM. For huge files, use the chunking method first, then group each chunk, or switch to pandas with groupby if your machine has enough memory.
Method 3: Using Pandas for Simplicity
If you already use pandas, splitting is a one-liner. This example splits by a column value and writes one CSV per group:
import pandas as pd
df = pd.read_csv('data.csv')
for key, group in df.groupby('country'):
group.to_csv(f'country_{key}.csv', index=False)
To split by row count, use numpy.array_split:
import pandas as pd
import numpy as np
df = pd.read_csv('large.csv')
chunks = np.array_split(df, 10) # 10 equal parts
for i, chunk in enumerate(chunks):
chunk.to_csv(f'part_{i+1}.csv', index=False)
Pandas loads the whole file into memory, so it is not ideal for files over a few gigabytes on a typical laptop. For most business exports (under 1 GB), it is the fastest to write and read.
How to Choose the Right Method
- File size under 1 GB, need simple row chunks: use the
csvmodule chunking method—it uses little memory. - File size under 1 GB, need grouping by column: use pandas
groupbyfor clarity. - File size over 1 GB, need grouping: use chunking plus a dictionary per chunk, or use a database like SQLite to query groups.
- Need to preserve exact formatting (quotes, line endings): stick with the
csvmodule; pandas may change quoting styles. - Need to split by header groups (e.g., every 5 columns): that is a transpose problem—read the first row, count columns, and write column slices.
Common Problems and Pitfalls
One frequent mistake is forgetting that csv.reader returns strings, so if you compare a numeric column to an integer, convert with int(row[0]). Another is newline handling: always open files with newline='' in Python 3, otherwise you get extra blank lines on Windows. Encoding issues also appear—if your file has special characters, specify encoding='utf-8' or encoding='latin-1' depending on the source. Finally, if your CSV has multiline fields (quoted text with line breaks), the csv module handles them correctly, but a naive readline() approach will break the file.
Performance and Memory Considerations
Reading a 5 GB CSV line by line with the csv module uses about 50–100 MB of memory. Pandas would need roughly 5–10 GB because it stores everything as objects. If you are on a server with limited RAM, always prefer the streaming approach. For very large files, you can also use csv.DictReader to access columns by name instead of index, which makes your code more readable but slightly slower. If you need to split a file into exactly N parts of roughly equal size, you can first count the total lines (excluding header) with a quick loop, then compute the chunk size.
Alternatives to Python
If you cannot use Python, the split command on Linux/macOS splits by lines: split -l 100000 large.csv part_. That produces files named part_aa, part_ab, etc., but it does not repeat the header in each file—you would need to add it manually. On Windows, PowerShell can do it with Get-Content and Select-Object -First, but it is slower and memory-hungry for big files. Excel itself can split by opening the file and copying ranges, but it is impractical beyond 1 million rows. For a one-off task, those tools work; for repeatable automation, Python is the better choice because you can save the script and run it on new files.
Frequently Asked Questions
Does splitting a CSV change the data types?
No, a CSV is plain text. Splitting it with Python just copies the text as-is, so numbers stay as strings, and dates stay as text. If you use pandas and then write to CSV, it may reformat numbers (e.g., adding trailing zeros) unless you specify float_format or keep everything as strings.
Can I split a CSV without loading it all into memory?
Yes, the csv module reads row by row, so you can split a file of any size as long as you write each chunk to disk before reading the next. The grouping method does load all rows, but you can avoid that by sorting the file first by the group column, then splitting on group changes.
How do I keep the header in every split file?
In the row-chunk method, read the header with next(reader) and write it to each output file before writing the rows. In pandas, use header=0 when reading and index=False when writing—the header is automatically included in each to_csv call.
What if my CSV uses semicolons or tabs as delimiters?
Pass the delimiter to the reader and writer: csv.reader(infile, delimiter=';') or pd.read_csv('file.csv', sep=';'). For tabs, use delimiter='\t' or sep='\t'.
Can I split a CSV by number of columns instead of rows?
Yes, but that means cutting the file vertically. Read the first row to get the column count, then for each output file, write a subset of columns for every row. This is rarely needed, but you can do it with the csv module by slicing each row list.
Is there a risk of data loss when splitting?
Only if you mishandle encoding or line endings. Always open files with newline='' and specify the correct encoding. Also, if your CSV has a trailing newline at the end, the last chunk will still be written correctly. Test on a small sample first to verify the row counts add up to the original total.
Related
- Color by Number Hot Air Balloon: How It Works
- How to Use split() Method in Java
- Split s2 in SQL? How to Split a String
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Maximum Number of Entries Has Been Reached? ExplainedNo, the message “Maximum number of entries has been reached” is not a universal limit—it is a specific…
- Job Task List Template in Excel: How to Build and Use ItA job task list template in Excel is a worksheet for recording tasks, owners, due dates, priorities, and…
- Google Sheets Duplicate Rows: Find and Remove ThemYes. In Google Sheets, select the data range and choose Data > Data cleanup > Remove duplicates to…
- Excel MAXIFS: Find the Highest Value for Each DateYes. In Excel, use MAXIFS to return the largest value from rows whose date matches a chosen date.…
- Create a Signature in Outlook 365: Step-by-Step GuideTo create an email signature in Outlook 365, open the signature settings for your version of Outlook, write…
- Excel Power Query: Merge 3 TablesTo merge three tables in Excel Power Query, you perform two sequential merge operations: first merge two tables,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.