๐ File Operations ยท 6 min read
How to Split a CSV by Column Value (One File per Category)
Pick the column, group the rows by its values, and write one file per group with the header repeated in each. That is the whole operation, and there are three ways to do it: filter-and-copy in a spreadsheet, a short Python script, or a browser splitter that takes the column name as an input. The method matters less than the two things people get wrong: filenames built from data, and no way to prove that every row landed somewhere.
If what you actually need is a size cut, because a program refuses anything above a certain number of rows, that is a different job and splitting a large CSV by size covers it. This page is for the case where the file has to come apart along a category: one file per region, per salesperson, per client, per month.
First, decide what counts as a distinct value
The number of output files is the number of distinct values in that column, after you decide how to treat case and whitespace. A column holding North, north and North looks like three categories to a strict comparison and one to a human. Trim the whitespace and normalise the case first, or you will finish with three files that should have been one.
Two edge cases are worth settling before the split rather than after. Rows where the column is empty: they form their own group, and the tool will try to name the file after nothing. And columns with a high cardinality, such as an order ID or a timestamp, where the number of distinct values runs into the thousands and you get thousands of files.
Method 1: Excel, for a file you can see the end of
Workable up to roughly a few thousand rows and a handful of categories, painful beyond that.
- Sort the table by the column you are splitting on, so equal values sit together.
- Turn on Data โ Filter and pick one value. Copy the visible rows, paste them into a new sheet, and save that sheet as CSV.
- Repeat for every value.
The failure mode here is the filter itself: copying a filtered range can bring hidden rows with it depending on how you select, and pasting into a new sheet silently drops the header unless you copy it too. Both mistakes produce files that look right and are wrong, which is worse than an obvious error.
Method 2: a browser splitter, for a one-off
Point the tool at the file, name the column, and it writes a zip with one CSV per value. Nothing to install and nothing leaves the browser when the tool runs client-side. Ours does the grouping and the size cut in the same pass, so a category that is still too large for the destination program can be chunked at the same time: CSV splitter.
Check what the tool does with the header row before you run it, and check whether it quotes fields that contain commas. A splitter that writes unquoted output will corrupt any row whose address or product name contains a comma, and the damage only shows up when the file is read back.
Method 3: Python, when it has to run again next month
The csv module in the standard library handles the quoting rules for you, which is the reason to use it rather than splitting lines by hand. RFC 4180, the document that registers the format, allows a field to contain the delimiter or a line break as long as the field is wrapped in double quotes, so a file can have fewer physical lines than records.
import csv, os, re
from collections import defaultdict
src = "orders.csv"
col = "region"
out = "split"
rows = defaultdict(list)
with open(src, newline="", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
fieldnames = reader.fieldnames
for row in reader:
rows[(row[col] or "blank").strip()].append(row)
os.makedirs(out, exist_ok=True)
for value, group in rows.items():
safe = re.sub(r'[\\/:*?"<>|]', "_", value).strip(". ")
path = os.path.join(out, f"{safe or 'blank'}.csv")
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(group)
print(f"{value!r} -> {len(group)} rows")Three details in that script are doing real work. newline="" on both the reader and the writer stops the csv module from doubling line breaks on Windows. encoding="utf-8-sig" on the input swallows the byte order mark that Excel writes when it saves CSV, which otherwise ends up glued to the first header name. And the re.sub call strips the characters that cannot appear in a Windows filename.
The filename problem is the real one
Every tool that writes one file per value is copying data into a filename, and data does not respect the filesystem. These characters are refused by Windows and are worth removing everywhere so the same output works on any machine: \ / : * ? " < > |.
Dates are the usual culprit. A value like 2026/11/05 creates a path three directories deep instead of a file, and macOS turns the colon in 2026:11:05 into something else again. Spaces at the start or end of a name, and a name ending in a period, also fail on Windows. Replace the offending characters with an underscore and trim the whitespace, then look at the list of output files before trusting them.
Verify the split before you delete the source
Count rows in, count rows out, and compare the totals. A simpler check with the same effect: concatenate the outputs back into one file and compare the row count with the original. If the two numbers differ, something was dropped or duplicated, and the source file is the only copy that can tell you which.
Also open two or three of the outputs and read the first rows. A file that starts with a header and continues with data is a good sign; a file that starts with data means the header was not written, and a file whose second column holds a date that belongs in the fourth column means the delimiter changed. Both are quick to spot and expensive to discover later.
Once the split is clean, the pieces are usually analysed rather than recombined, and the CSV analyzer will summarise any one of them without a spreadsheet in the way.
Frequently asked
What is the difference between splitting by rows and splitting by column value?
Splitting by rows cuts the file into equal pieces, so a 200,000-row file becomes four files of 50,000 rows whether or not a client or region is broken across the cut. Splitting by column value sorts first and writes one file per distinct value, so every row for a given region, client or month ends up together. Use the first when a program has a size limit, the second when a person or system downstream needs one file per category.
Do I need to sort the file before splitting by column value?
No, if the tool groups rows by the value it finds. Sorting first is what the manual spreadsheet method requires, because there you have to keep each group contiguous before copying it out. A script or a browser splitter that writes to a dictionary does not care about the original order, and the order inside each output file follows the input.
Why did some output files fail to save or open?
Almost always the filename. Column values are copied into file names by most tools, and values containing a slash, a colon, an asterisk, a question mark, a quote, a pipe or angle brackets are illegal in a Windows filename. Values with leading or trailing spaces, or a period at the end, also fail. Sanitise the value before it becomes a name, and decide in advance what to call rows where the column is empty.
How do I check that no rows were lost in the split?
Count the data rows in the source and in the outputs, and compare the totals. A line count is a poor check on a file with quoted multi-line values, because such a file has more physical lines than records. Counting records, or comparing the sum of the parts to the whole, catches both dropped rows and rows written twice.
Sources for this article: RFC 4180 for the delimiter, quoting and line-break rules, including the requirement that a field containing a separator or line break be wrapped in double quotes; Python's csv module documentation for DictReader, DictWriter and the newline="" requirement; and Microsoft documentation for the characters that are not permitted in Windows file names. No figures on this page are estimates.
Related reading
File Operations โ other guides that pair well with this one.
- CSV Writer Adding Blank Rows: Why csv.writer Puts an Empty Line Between Records
- How to Sum a Column in a CSV (Without Opening Excel)
- CSV File Has the Wrong Number of Columns? Find the Broken Row
- CSV Import Skipped Rows? Where They Went and How to Get Them Back
Browse all guides in the NoCodeCSV blog.