Writing CSV Import Code With LLMs in November 2026: Parse With a Real CSV Library, Validate Every Row Before Saving, and Report Errors by Line Number
"Let users upload a spreadsheet of their customers" sounds like an afternoon of work, and if you ask an LLM for it you will get code in seconds. The first draft usually splits each line on commas, assumes the columns are in a fixed order, inserts rows one at a time as it reads them, and stops with a stack trace on row 4,812 after saving the first 4,811. Every one of those choices causes a support ticket later.
This guide covers how to get CSV import code from an assistant that survives real files from real users: what to put in the prompt, which parts of the generated code to check first, and the tests that catch the usual mistakes. The examples use Python, but the same rules apply in Node, Ruby, Go, or PHP.
A good importer works like a mailroom: every incoming column goes into the slot named on its label, not the slot it happened to arrive in. Image: Mailroom by Htlcto, CC BY 2.0, via Wikimedia Commons.
Why CSV import is harder than it looks
CSV is not one format. It is a loose family of formats that share the idea of rows and separators. Files that users export from Excel, Google Sheets, Numbers, banking portals, and old CRMs differ in ways that break naive code:
- Quoted fields. A company name like
"Smith, Jones & Co"contains a comma inside quotes. Splitting on commas turns one column into two. - Line breaks inside fields. A notes column can contain a newline inside quotes, so one record spans two physical lines. Reading line by line breaks it.
- Encodings. Excel on Windows often saves CSV in a legacy encoding such as Windows-1252, or as UTF-8 with a byte order mark (BOM) at the start. A BOM silently glues itself to the first header name, so
emailbecomes\ufeffemailand your lookup for the "email" column fails. - Delimiters. In many European locales, spreadsheet apps use semicolons instead of commas because the comma is the decimal separator.
- Column order and naming. Users rearrange columns, rename them ("E-mail", "Email Address"), add extra ones, and leave blank columns on the right.
- Values. Dates arrive as
03/04/2026(March 4 or April 3?), numbers as1.234,50, phone numbers with leading zeros stripped by the spreadsheet, and booleans as "Yes", "Y", "TRUE", or "1".
An LLM knows all of this if you ask, but it will not volunteer it in a short prompt. The fix is to describe the job precisely.
Step 1: Write a prompt that describes the real input
Give the model the target schema, a few real (anonymized) sample rows, and the behavior you want when things go wrong. A prompt like this works far better than "write a CSV importer":
Write a Python function import_contacts(file_bytes, account_id) for a Django app.
Target model: Contact(account_id, email [unique per account], name,
phone, signed_up_on [date], is_vip [bool]).
Requirements:
- Parse with the csv module (no manual splitting). Detect a UTF-8 BOM;
try UTF-8 first, fall back to cp1252, and report which was used.
- Map headers case-insensitively with aliases: "e-mail", "email address"
-> email; "full name" -> name. Unknown columns are ignored and listed.
- Validate every row first. Do not write anything until all rows are checked.
- Collect errors as (line_number, column, message). Line numbers must
match what the user sees in a spreadsheet (header is line 1).
- If any row fails, save nothing and return the error list.
- If all rows pass, upsert by (account_id, lower(email)) in batches of 500
inside one transaction.
- Reject files over 5 MB or 20,000 rows before parsing.
Sample rows (anonymized):
Full Name,E-mail,Phone,Signed up,VIP
"Lee, Dana",dana@example.com,0412 555 010,2026-03-04,Yes
Sam Ortiz,SAM@EXAMPLE.COM,,04/03/2026,no
The sample rows matter. They show the model the quoted comma, the uppercase email, the empty phone, and the two date formats, so it has to handle them instead of guessing.
Step 2: Check that it uses a real parser
The first thing to look for in the generated code is how it reads rows. You want the language's CSV library, not line.split(",") or a regular expression. In Python that means the csv module with a text stream:
import csv, io
def decode(file_bytes):
for enc in ("utf-8-sig", "cp1252"):
try:
return file_bytes.decode(enc), enc
except UnicodeDecodeError:
continue
raise ValueError("Could not read the file. Save it as CSV UTF-8 and try again.")
text, encoding = decode(file_bytes)
sample = text[:4096]
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
except csv.Error:
dialect = csv.excel
reader = csv.DictReader(io.StringIO(text, newline=""), dialect=dialect)
Three details to confirm:
utf-8-sigstrips a BOM if present and behaves like plain UTF-8 if not. Without it, the first header name gets an invisible character in front.- Note that cp1252 decoding rarely fails, so it works as a last resort, not as detection. Order matters: try UTF-8 first.
- The text stream is opened with
newline="", which the Python docs require so that line breaks inside quoted fields are handled correctly.
In Node, the equivalent is a maintained library such as csv-parse or Papa Parse rather than splitting strings. If the assistant writes its own parser, ask it to replace it with a library.
Step 3: Map headers, do not trust column order
Code that reads row[0] as the name and row[1] as the email breaks the first time a user reorders columns. Ask for a header map built once, before reading data:
ALIASES = {
"email": {"email", "e-mail", "email address"},
"name": {"name", "full name"},
"phone": {"phone", "phone number", "mobile"},
"signed_up_on": {"signed up", "signup date", "signed_up_on"},
"is_vip": {"vip", "is_vip"},
}
def build_header_map(fieldnames):
mapping, unknown = {}, []
for raw in fieldnames or []:
key = (raw or "").strip().lower()
field = next((f for f, names in ALIASES.items() if key in names), None)
if field and field not in mapping.values():
mapping[raw] = field
elif key:
unknown.append(raw)
missing = {"email"} - set(mapping.values())
return mapping, unknown, missing
If a required column is missing, stop right away with a message that names it ("The file needs an Email column"). Show the unknown columns too, so a user who named the column "Mail" understands why nothing matched.
Step 4: Validate everything before saving anything
The most important design choice is all-or-nothing. If the importer saves rows as it goes and fails halfway, the user is left with half an import, fixes the file, uploads again, and now has duplicates or a confusing mix. Validate the whole file first, collect every error, and only write when the list is empty.
from datetime import datetime
DATE_FORMATS = ("%Y-%m-%d",) # add others only after you decide how to resolve ambiguity
TRUE, FALSE = {"yes", "y", "true", "1"}, {"no", "n", "false", "0", ""}
def validate(reader, mapping):
rows, errors, seen = [], [], set()
for line_no, raw in enumerate(reader, start=2):
rec = {mapping[k]: (v or "").strip() for k, v in raw.items() if k in mapping}
if not any(rec.values()):
continue # skip blank lines
email = rec.get("email", "").lower()
if "@" not in email:
errors.append((line_no, "email", f"'{rec.get('email', '')}' is not a valid email"))
elif email in seen:
errors.append((line_no, "email", "appears more than once in this file"))
seen.add(email)
signed = None
if rec.get("signed_up_on"):
for fmt in DATE_FORMATS:
try:
signed = datetime.strptime(rec["signed_up_on"], fmt).date()
break
except ValueError:
pass
if signed is None:
errors.append((line_no, "signed_up_on", "use the format YYYY-MM-DD"))
vip = rec.get("is_vip", "").lower()
if vip not in TRUE | FALSE:
errors.append((line_no, "is_vip", "use Yes or No"))
rows.append({"email": email, "name": rec.get("name", ""),
"phone": rec.get("phone", ""), "signed_up_on": signed,
"is_vip": vip in TRUE})
return rows, errors
Things to check in whatever version the model writes:
- Line numbers match the spreadsheet. The header is line 1, so the first data row is line 2. One caveat: if a quoted field contains a newline, the record spans two physical lines. Python's
reader.line_numreports the physical line where the record ended; decide which number you show and test it. - Ambiguous dates are refused, not guessed.
04/03/2026means different days in the US and the UK. Either accept only an unambiguous format, or let the user pick the format on the upload screen. Never let the code silently pick one. - Duplicates inside the file are caught before they hit a unique constraint and abort the transaction with a database error the user cannot read.
- Error messages say what to do. "Line 14, Email: 'dana@' is not a valid email" is useful. "ValidationError" is not.
Step 5: Write in batches inside one transaction
Once validation passes, insert or update the rows. Inserting one row per query is slow for a 20,000-row file, and doing it outside a transaction brings back the half-import problem. Ask for a batched upsert in a single transaction:
from django.db import transaction
def save(rows, account_id, batch=500):
with transaction.atomic():
for i in range(0, len(rows), batch):
chunk = [Contact(account_id=account_id, **r) for r in rows[i:i + batch]]
Contact.objects.bulk_create(
chunk,
update_conflicts=True,
unique_fields=["account_id", "email"],
update_fields=["name", "phone", "signed_up_on", "is_vip"],
)
Check that the unique key the code upserts on matches a real unique constraint or index in the database; with PostgreSQL, ON CONFLICT requires one. Also check that the email is normalized the same way in the file and in the database (here, lowercased before saving), or "Sam@example.com" and "sam@example.com" become two contacts.
Make sure the account_id comes from the logged-in user's session, never from a column in the file. A CSV is user input; a row that says account_id=7 should not be able to write into someone else's account.
Inspect everything at the border: validate every row before any of it is allowed into the database. Image: Customs man at work, N.D.L. Line pier, New York by Bain News Service (Library of Congress), Public domain, via Wikimedia Commons.
Step 6: Set limits and move big files off the request
An upload handler that reads the whole file into memory and parses it during the web request is fine for a few hundred rows. For larger files it times out or uses too much memory. Ask the model for:
- A size cap checked before reading the body, and a row cap checked while parsing.
- For files above a few thousand rows, saving the upload to storage and processing it in a background job, with an import record that tracks status (queued, validating, failed, done) and stores the error list.
- A preview step: show the first ten parsed rows and the detected column mapping, and let the user confirm before the real import runs. This catches swapped columns and wrong date formats before anything is saved.
Step 7: Test with the ugly files
Ask the assistant to write tests, and give it the list of cases. These are the ones that catch real bugs:
- A file saved by Excel as "CSV UTF-8", which starts with a BOM.
- A file in cp1252 with an accented name such as "José".
- A semicolon-delimited file.
- A quoted field containing a comma, and another containing a newline.
- Columns in a different order, with different capitalization, plus one extra column.
- A missing required column.
- The same email twice with different capitalization.
- An invalid row near the end of the file: assert that nothing was saved.
- Trailing empty rows and a trailing empty column, which spreadsheets often add.
- A file one byte over the size limit.
Keep these fixtures as small files in your test directory. When a user reports a file that failed, add an anonymized copy as a new fixture before fixing the bug.
A note on spreadsheet formulas
Formula injection, where a cell starting with =, +, -, or @ runs as a formula when opened in a spreadsheet, is mostly an export problem. But if you import data and later export it again, or show it to other users who download it, the risk carries through. Decide whether to reject such values on import, store them as-is and escape them on export, or both, and make sure the generated code matches that decision.
Review checklist
Before you merge LLM-written import code, confirm:
- It parses with a CSV library, handles a BOM, and opens text with
newline=""(or the library's equivalent). - Columns are matched by header name with aliases, not by position.
- Every row is validated before any row is saved, and one transaction wraps the writes.
- Errors list line number, column, and a plain-language fix.
- Ambiguous dates and numbers are rejected or resolved by an explicit user choice.
- Duplicates in the file are detected, and upserts use a real unique constraint.
- Ownership fields come from the session, not the file.
- Size and row limits exist, and large files run in a background job.
- Tests cover the ugly files listed above.
An LLM can write all of this quickly. What it cannot do is know which files your users actually have. Feed it real samples, insist on all-or-nothing validation, and keep a folder of the files that broke your importer. That folder ends up being the most valuable part of the feature.
Comments
Post a Comment