Fix Python CSV Imports: BOM, Delimiters and Newlines
Diagnose Python CSV import errors in order: UTF-8 BOM, delimiters, quoting, newlines and schema checks. Includes a tested validator and reproducible fixture.
For a known UTF-8 CSV feed, open with encoding="utf-8-sig" and newline="", parse with an explicit dialect, and validate headers and field counts before converting values. A parser success alone does not establish that identifiers, missing values or decimal amounts are correct.
Locate the failure before changing the parser
A CSV import can finish without an exception and still damage its data. The most useful first question is therefore not “Which option makes this load?” It is “Which boundary changed the meaning?” Treat the input as four boundaries: bytes become text, text becomes records, records become named fields, and field strings become business values. A successful later boundary cannot repair an earlier mistake.
For example, a report may show one enormous column because the delimiter is wrong, an apparently missing customer_id because its name contains an invisible prefix, or fewer customers because identifiers lost leading zeroes. These are separate defects. Changing encoding, delimiter and numeric conversion together makes it harder to establish which change was necessary.
Work from a retained copy of the original export. Record its producer, export settings and expected columns. Build a tiny synthetic reproduction containing the troublesome feature, rather than sharing customer records in logs or support tickets. Compare the parsed values with the export contract before connecting the importer to a database.
| Observation | First boundary to inspect | Useful evidence |
|---|---|---|
| UnicodeDecodeError | Bytes → text | Producer encoding and a small byte prefix |
| One field per row | Text → records | Delimiter and raw header |
| KeyError for a visible header | Records → names | repr() of each header name |
| Shifted columns or extra rows | Record structure | Quotes, embedded newlines and field counts |
| 00123 becomes 123 | Business conversion | Identifier stored as text |
Check the BOM without hiding decoding errors
Inspect a small prefix in binary mode before trying another encoding. The diagnostic below reads only four bytes; it does not print the file body. A prefix beginning b"\xef\xbb\xbf" is the UTF-8 signature. With plain UTF-8 decoding, that signature can remain as U+FEFF at the start of the first header. It is easy to miss when viewing the name normally.
For a producer that promises UTF-8 with an optional signature, encoding="utf-8-sig" handles both cases. It consumes the signature only at the beginning. It does not remove arbitrary invisible characters from every value, and it does not decode UTF-16 or legacy Windows exports correctly by magic. Establish those encodings from the export settings instead.
Keep decoding strict. errors="ignore" can silently delete bytes; errors="replace" can insert replacement characters. Either can alter a key while leaving the import apparently successful. A Latin-1 fallback accepting a byte sequence is also insufficient evidence that the text is correct. If decoding fails, stop and obtain the encoding contract or a new export.
from pathlib import Path
with Path("orders.csv").open("rb") as stream:
print(repr(stream.read(4)))
# Once UTF-8 is established, inspect names without losing invisible marks.
import csv
with open("orders.csv", encoding="utf-8-sig", newline="") as stream:
header = next(csv.reader(stream), [])
print([repr(name) for name in header])A physical line is not necessarily a CSV record
A quoted note can contain a comma, a double quote or an actual line break. RFC 4180 describes the familiar comma-and-double-quote convention, including doubled quotes inside quoted fields. Consequently, splitting each physical line with split(",") is not a safe substitute for a CSV parser. Splitting the whole file with splitlines() before parsing can also discard the line endings that belonged inside a field.
Open the text stream with newline="" and let the csv module interpret record boundaries. This matters on output as well as input. It also lets a quoted CRLF in the fixture below remain CRLF instead of being normalized by the text layer. When reporting a failure, distinguish the logical record count from reader.line_num, which measures physical lines consumed.
A semicolon-delimited export needs delimiter=";"; a tab-delimited export needs delimiter="\t". Confirm the producer setting and header before guessing. Sniffer is useful for exploration, but a short or unusual sample can be unrepresentative, and has_header is heuristic. For a recurring feed, store the agreed dialect explicitly and reject a changed layout.
Make the input contract executable
The example contract is intentionally narrow: exactly three columns in a fixed order, five ASCII digits for customer_id, a nonnegative amount with two decimal places and at most nine integer digits, and a free-text note. Customer identifiers remain strings. A duplicate identifier is rejected for this demonstration; a real order feed would normally have its own order identifier and duplicate policy.
Save the following as import_orders.py. It returns validated rows without writing to a destination. Exact header comparison catches missing, duplicated, reordered and unexpected names, including whitespace changes. Exact row length catches missing or extra fields. Blank physical lines are skipped by csv.reader; a parsed record with empty fields is still checked.
This is a small-file teaching importer, not a universal validator. strict=True catches certain malformed CSV structures but does not enforce the business schema. The explicit checks do that. Some producers allow extra columns or reordered names; implement that policy deliberately rather than silently accepting it.
import csv
import re
from decimal import Decimal
EXPECTED = ["customer_id", "amount", "note"]
def read_orders(path, *, delimiter=","):
"""Validate a small, trusted-size UTF-8 export before returning rows."""
result = []
seen = set()
with open(path, encoding="utf-8-sig", newline="") as stream:
reader = csv.reader(stream, delimiter=delimiter, strict=True)
try:
header = next(reader)
except StopIteration:
raise ValueError("empty file") from None
if header != EXPECTED:
raise ValueError("header must be customer_id, amount, note in order")
for record_number, row in enumerate(reader, start=2):
location = (f"record {record_number}, "
f"ending at physical line {reader.line_num}")
if len(row) != len(EXPECTED):
raise ValueError(f"{location}: expected three fields")
customer_id, raw_amount, note = row
if not re.fullmatch(r"[0-9]{5}", customer_id):
raise ValueError(f"{location}: invalid customer_id")
if customer_id in seen:
raise ValueError(f"{location}: duplicate customer_id")
if not re.fullmatch(r"[0-9]{1,9}\.[0-9]{2}", raw_amount):
raise ValueError(f"{location}: invalid amount")
seen.add(customer_id)
result.append({"customer_id": customer_id,
"amount": Decimal(raw_amount), "note": note})
if not result:
raise ValueError("no data records")
return result
Source: Python csv module: readers, dialects and parser behavior ↗
Generate a fixture with a BOM, quotes and a multiline field
Run this second script beside import_orders.py in a temporary working directory. It creates orders-demo.csv exclusively, so rerunning it with the same file present raises FileExistsError. Remove only your disposable fixture or choose a new filename. The writer creates quoting correctly; you do not need to count quote characters by hand.
The expected result is “Validated 2 records.” The assertions check what the importer preserves, not merely whether it runs: a zero-prefixed identifier, a comma plus embedded quotes, a CRLF inside one note, and decimal scale. We ran this exact fixture locally. It is synthetic and does not represent a customer dataset or a production throughput test.
import csv
from pathlib import Path
from import_orders import read_orders
path = Path("orders-demo.csv")
# Exclusive creation protects an existing file with the same name.
with path.open("x", encoding="utf-8-sig", newline="") as stream:
writer = csv.writer(stream)
writer.writerow(["customer_id", "amount", "note"])
writer.writerow(["00123", "12.50", 'Call, then say "hello"'])
writer.writerow(["00456", "0.00", "first line\r\nsecond line"])
rows = read_orders(path)
assert rows[0]["customer_id"] == "00123"
assert rows[0]["note"] == 'Call, then say "hello"'
assert rows[1]["note"] == "first line\r\nsecond line"
assert str(rows[0]["amount"]) == "12.50"
print("Validated", len(rows), "records")
Convert values only after the structure passes
An identifier that looks numeric is still an identifier. Converting 00123 to an integer loses information even when the arithmetic value is unchanged. Keep account numbers, postal codes and product codes as text unless the receiving schema explicitly says otherwise. Do not apply strip() to every field automatically: spaces in a note may be intentional, while spaces in a header may signal a changed export.
The amount grammar here rejects commas, exponents, signs, NaN and Infinity before conversion. Decimal constructed from the validated string avoids first passing through a binary float. This does not define a general currency model: the contract omits currencies, negative adjustments and rounding. If the producer exports 12,50, agree whether that is a decimal comma and whether the separator is semicolon before adapting the grammar.
Empty text, a missing field and the literal word NULL should also have distinct policies. In this importer an empty note is allowed, a missing note column is rejected, and NULL in a note remains ordinary text. Do not let a generic missing-value rule invent business meaning. Resolve that meaning with the receiving system before loading.
Source: Python decimal: decimal arithmetic and string conversion ↗
Test rejection paths before allowing a write
Create variants of the fixture one defect at a time: duplicate the header name, add a fourth field, remove the amount, repeat a customer identifier, use 12,50 as an amount, and leave a quoted field unfinished. Each should fail for an understandable reason. Test a valid semicolon file with delimiter=";" and then deliberately use the default comma to confirm that the header guard stops it.
Our local checks covered BOM and non-BOM UTF-8, comma/semicolon/tab delimiters, LF and CRLF records, Unicode notes, quoted commas and quotes, multiline preservation, empty notes, and rejection of malformed schemas and values. The tests also confirmed strict decoding rejects invalid UTF-8. These checks establish the behavior of this fixture and parser, not compatibility with every spreadsheet exporter.
If validation fails midway, this function has not committed any rows. Keep that separation when adding a database: validate into a staging area, then publish the accepted batch transactionally according to your database design. Writing each row immediately would let a late error leave a partially imported file. An automatic retry could then create duplicates.
Set boundaries for larger or untrusted uploads
This implementation accumulates rows and a duplicate-key set in memory. For a large file, define upload-byte, record, column and field limits before processing it. The csv parser has a field-size limit; increasing it to bypass an error without understanding the input can mask a broken export. Streaming rows reduces one memory cost but does not by itself solve duplicate detection or atomic publication.
Log a file identifier, the agreed encoding and dialect, counts, and the failing record location. Avoid logging full notes or raw rows. When the structure is damaged, a reported physical line is a diagnostic location, not proof that exactly one source row caused the problem. Quarantine the original file for an authorized operator to inspect.
A CSV writer handles CSV quoting. That is separate from the way a spreadsheet interprets cell text as formulas. If the destination is a spreadsheet and values come from untrusted people, define a separate export policy for that destination; this importer does not sanitize spreadsheet formulas.
A repeatable repair sequence
Start with the original bytes and a known encoding. Confirm the dialect and preserve record boundaries. Validate the header and field counts before assigning business types. Then prove that representative values survive unchanged and that rejected inputs cannot create partial output. This order turns “the CSV looks wrong” into a specific, reproducible failure.
Keep the small fixture with the importer when the export contract changes. Add the new edge case before relaxing a rule, and document why the receiving system accepts it. If the script cannot import its own modules, use the related Python environment troubleshooting guide first; if accepted rows later behave unexpectedly in SQL, examine the related NULL and pagination guides.
Your next steps
- Diagnose bytes, record structure, schema and business conversion separately.
- Preserve identifiers and quoted multiline text; validate before committing output.
- Use a small synthetic fixture to test both accepted and rejected inputs.
Sources & official resources
Linked resources checked on 2026-10-25. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →