Files and formats

Part of the free LogicWiz Data Engineering course, Module 3: Python for data wrangling. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 8:40 on Wednesday. Tess forwards a customer list that marketing saved from Excel. Your script dies with KeyError: 'customer_id', yet the column is right there in the first line. The same morning Dana's 1,000,000-line export loads as 999,412 rows, and nothing complains. Nora looks at both and says: "Neither bug is in your code. Look underneath it, at the bytes."

You'll learn to

  • Read and write CSV and JSON Lines with the standard library
  • Explain how bytes become text, and spot a wrong encoding
  • Predict what the CSV reader does with quotes and line breaks
  • Say why pipelines prefer JSON Lines

Learn

Start with a file that behaves

Before the two broken files, read a good one. This module uses only Python's standard library: no pandas. Python interview rounds ask for exactly that, and every bigger tool is built on the same layer. Spark and DuckDB start the way you are about to: read bytes, turn them into text, split the text into rows.

csv.DictReader hands you each row as a dict, with the header as keys. Two habits go with it. Open the file in a with block, so it is closed even if your code fails. And pass newline="", as the csv documentation asks: the reader then sees the real line endings, and a line break inside a quoted value stays part of the value.

Read the orders export

import csv

with open("data/orders.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

print(len(rows), "rows")
print(rows[0])
print(type(rows[0]["order_id"]))

80 rows, each one a dict. Look at the last line of output: order_id is a str. CSV has no types, only text, and the csv module does not guess. An empty field arrives as "", never as None.

Everything from a CSV is a string. "10" > "9" is False, because strings compare character by character and "1" comes before "9". Sorting, max() or adding text numbers gives nonsense with no error: "2" + "3" is "23". Convert on purpose as you read: int(row["qty"]), float(...), or Decimal(...) for money (Lesson 3.6).

Case one: the column that vanished

Now Tess's file. Its header reads customer_id,name,city, and row["customer_id"] raises KeyError. How?

Because a file is not text. A file is bytes, and Python turns them into text with a decoder that you pick in open(..., encoding=...). The same bytes, read by a different decoder, give different text.

Excel's "CSV UTF-8" export puts three extra bytes at the very start of the file: EF BB BF. They are called the byte order mark, or BOM. A spreadsheet never shows them. Look at where they sit in the picture.

The first 51 bytes of Tess's file

Two byte bars on one scale: the header line starts with the three-byte BOM before customer_id, and the data line spends two bytes each on the accented letters in Zoë and Montréal.

Each bar is one line of the file, drawn byte by byte. The red block is the BOM: three bytes before the letter c. The amber blocks are letters that take two bytes each.

Two decoders on Tess's file, then two wrong ones

import csv

for enc in ["utf-8", "utf-8-sig"]:
    with open("exports/customers_excel.csv", newline="", encoding=enc) as f:
        reader = csv.DictReader(f)
        print(enc, reader.fieldnames)

print("São Paulo".encode("utf-8").decode("cp1252"))
try:
    "Montréal".encode("cp1252").decode("utf-8")
except UnicodeDecodeError as e:
    print(e)
print("Montréal".encode("cp1252").decode("utf-8", errors="replace"))

Lines 1 and 2: utf-8 keeps the BOM as \ufeff on the first name, and utf-8-sig drops it. utf-8-sig also reads a file with no BOM exactly like utf-8, so it is safe for both. The last three lines point a decoder at the wrong bytes. The next section takes them one at a time.

One wrong decoder shouts, the other whispers

Two encodings cause most of the trouble. UTF-8 is the modern one. It uses 1 byte for plain English letters and 2 to 4 bytes for most others: é is the two bytes C3 A9. cp1252 comes from older Windows tools and always uses 1 byte: é is E9.

Mix them up, and the two mistakes behave very differently.

Read a cp1252 file as UTF-8 and Python stops: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 5: invalid continuation byte. Annoying, but honest.

Read a UTF-8 file as cp1252 and nothing fails. You get São Paulo, and it loads into the warehouse. That garbled text has a name: mojibake.

One letter, two decoders

The letter é saved as UTF-8 is the bytes C3 A9: the UTF-8 decoder reads é and the cp1252 decoder reads two wrong letters with no error. Saved as cp1252 it is the byte E9: cp1252 reads é and UTF-8 raises an error.

  1. Saved as UTF-8. The letter é goes into the file as two bytes: C3 A9. Nothing has read them yet.

  2. The right decoder. UTF-8 sees C3, knows a second byte belongs to it, and gives back é.

  3. The wrong decoder. cp1252 believes every byte is one letter. C3 is à and A9 is ©, so you get é. No error is raised: this is mojibake.

  4. Now the other way round. Saved as cp1252, the same letter is one byte: E9. cp1252 reads é. UTF-8 takes E9 as the start of a longer letter, finds that the next byte does not fit, and raises UnicodeDecodeError.

The left box is what is on disk. The other two boxes are what your program sees, depending on the encoding= you passed.

Remember: name the encoding every time you open a file. For anything that may have passed through Excel, use utf-8-sig.

Case two: a million lines, 999,412 rows

Now Dana's export. A million lines went in. 999,412 rows came out. No error.

The first thing to know: a line is not a row. CSV lets a value contain a comma, or even a line break, as long as the value is wrapped in double quotes. So "Mug, large" is one value, not two.

That is why you never cut a CSV line with split(","). Run the card and watch one product fall into four pieces.

Why not split on commas?

import csv

with open("exports/products_extra.csv", newline="") as f:
    lines = f.read().splitlines()
print("split:", lines[1].split(","))

with open("exports/products_extra.csv", newline="") as f:
    for row in csv.reader(f):
        print("csv:  ", row)

split cuts "Mug, large" in two, and every later column moves one place to the right. The csv module knows about quotes, doubled quotes and line breaks inside values. Use it every time, for writing too.

How the reader reads: one character at a time

So how does csv.reader know when a comma is data and when it ends a value? It reads one character at a time and remembers where it is. It is always in one of four situations, which programmers call states.

At the start of a value. In the middle of a plain value. Inside quotes. Or right after a quote inside quotes, waiting to see what comes next.

The rule that matters: inside quotes, a comma and a line break are ordinary characters. Only a closing quote gets the reader out. Follow the arrows in the picture.

Inside csv.reader: four states

The CSV reader moves from START_FIELD into IN_FIELD on an ordinary character or into IN_QUOTED_FIELD on a quote; inside quotes, commas and newlines are data until a closing quote, after which a comma saves the field and a newline saves the record.

Start at the grey box and follow one arrow per character. The state names are the real ones from CPython's Modules/_csv.c. Look at the amber IN_QUOTED_FIELD box: no comma or newline arrow leaves it. Only a quote does.

A quote that never closes

A four-line CSV file is read line by line: the header becomes a row, line 2 opens a quote, lines 3 and 4 are swallowed into the same value, and at the end of the file the reader returns 2 rows with no error.

  1. Line 1. No quotes. Each comma ends a value, and the line break ends the row. Row 1 is the header.

  2. Line 2 opens a quote. The reader is now inside quotes. The comma after Mug is data. So is the line break at the end: this row is not finished.

  3. Lines 3 and 4 are swallowed. Still inside quotes, so every comma and line break is added to the same value. Two products vanish into one field.

  4. End of file. No closing quote ever came. The reader hands over what it has and says nothing: 2 rows instead of 4. With strict=True it raises unexpected end of data instead.

The left box is the file, line by line. The right box is what your program gets. This is Dana's export in miniature: lines go missing inside other rows' values.

Four edge cases, run for real

import csv, io

bad = 'id,name\n1,"Mug, large\n2,Tea Towel\n3,Cup\n'
rows = list(csv.reader(io.StringIO(bad)))
print("unbalanced quote:", len(rows), "rows", rows[1])
try:
    list(csv.reader(io.StringIO(bad), strict=True))
except csv.Error as e:
    print("strict=True:", e)

two_lines = 'id,note\n1,"line one\nline two"\n2,ok\n'
print("lines:", len(two_lines.splitlines()), "records:", len(list(csv.reader(io.StringIO(two_lines)))))

spaced = 'a, b\n1, "x, y"\n'
print(list(csv.reader(io.StringIO(spaced)))[1], list(csv.reader(io.StringIO(spaced), skipinitialspace=True))[1])

try:
    list(csv.reader(io.StringIO("a\n" + "x" * 200_000 + "\n")))
except csv.Error as e:
    print("huge field:", e, "| limit:", csv.field_size_limit())

Output line 1 is the picture you stepped through. Line 2: strict=True turns the silence into an error. Line 3: a line break inside quotes that do close is fine, so 4 lines make 3 rows. Line 4: a space before a quote stops the quote from counting, unless you pass skipinitialspace=True. Line 5: a value over 131,072 characters raises until you call csv.field_size_limit(n).

There is no one CSV

One more reason CSV bites: nobody ever agreed on it. A document called RFC 4180 describes the common form: commas, double quotes, and "" for a quote inside a quoted value. Every exporter bends it. European spreadsheets often write ; between values and a comma inside numbers: 12,50.

Python calls one set of such rules a dialect. csv.Sniffer().sniff(sample) can guess a file's dialect, and the documentation itself calls its has_header check "a rough heuristic".

So guess once, while you build the loader. Then write the dialect into your code. A guess that changes when the data changes is a bug waiting for a quiet day.

What goes wrong, what you see, what to do

InputWhat the reader doesSymptomDefence
A quote that never closesStays in INQUOTEDFIELD to the end of the fileFewer rows, one giant value, no errorstrict=True; alert when rows read differ from the source count
A newline inside quotesKeeps it as data (with newline="")wc -l is higher than the row count: correctCount records with the parser, never with lines
, "x, y": space before the quoteTreats the quote as textColumns shift rightskipinitialspace=True or fix the exporter
A field over 131,072 charactersRaises field larger than field limit (131072)The load stops on one rowRaise csv.fieldsizelimit, or reject the row
; with a decimal commaSplits on commas inside numbersWrong column countPin delimiter=";" and parse 12,50 on purpose

In every row the reader does exactly what its rules say. The fix is never "guess harder". Write the rules into your code, and compare the number of rows you read with the number the source says it sent.

JSON Lines: one record per line

When you can choose the format, do not choose CSV. JSON keeps what CSV loses: numbers stay numbers, and there are true, false, null, lists and objects inside objects.

A plain JSON file holds one document, often one huge list, and json.load(f) reads all of it at once. Pipelines prefer JSON Lines (.jsonl, also called newline-delimited JSON): one complete JSON object on each line. You read it a line at a time with json.loads(line).

That buys three things. A writer can add a record without rewriting the file. A reader can go through it without loading everything. And one broken line does not ruin the rest. Call json.load on a JSON Lines file and it fails with "Extra data": it met a second object it did not expect.

Read JSON Lines

import json
from collections import Counter

statuses = Counter()
with open("data/payments.jsonl", encoding="utf-8") as f:
    for line in f:
        if not line.strip():
            continue
        p = json.loads(line)
        statuses[p["status"]] += 1

print(statuses)
print(type(p["amount"]), type(p["order_id"]))

SwiftKart's data/payments.jsonl: 70 captured, 8 refunded, 7 failed. Look at the types on the last line: amount is a float and order_id an int, with no conversion from you. Skipping blank lines keeps the reader safe when a file ends with an extra newline. Lesson 3.2 measures what this parsing costs.

CSV in, JSON Lines out

import csv, json

with open("data/orders.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

with open("orders.jsonl", "w", encoding="utf-8") as f:
    for row in rows:
        row["order_id"] = int(row["order_id"])
        row["customer_id"] = int(row["customer_id"])
        f.write(json.dumps(row) + "\n")

with open("orders.jsonl", encoding="utf-8") as f:
    print(f.readline().strip())

with open("small.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["order_id", "status"])
    writer.writeheader()
    writer.writerows({"order_id": r["order_id"], "status": r["status"]} for r in rows[:2])
    writer.writerow({"order_id": 9, "status": 'say "hi", twice'})
print(repr(open("small.csv", newline="").read()))

Writing mirrors reading. The first output line is an order as JSON, with real ints. The second shows what the CSV writer did: it quoted only the value that needed it, doubled the quotes inside it, and ended every row with \r\n. Convert types when you read, choose the format when you write.

Numbers to remember

Setting or factDefault or valueWhat it means
delimiter,the character between values
quotechar, doublequote", Truea quote inside a quoted value is written ""
escapechar, skipinitialspace, strictNone, False, Falseno escape character; a space before a quote breaks it; bad quoting is not an error
quotingQUOTEMINIMALthe writer quotes only the values that need it
lineterminator"\r\n"what the writer ends rows with; the reader ignores it and accepts \r or \n
csv.fieldsizelimit()131,072 charactersa longer value raises field larger than field limit (131072)
UTF-8 bytes per character1 for ASCII, 2 for é, 2 to 4 for most other scriptscp1252 always uses 1
The BOMEF BB BF, read as \ufeffutf-8-sig drops it
open() without encoding=locale.getpreferredencoding(False)the computer's own default, often cp1252 on Windows; Python 3.15 makes UTF-8 the default (PEP 686)
errors="replace"bad bytes become \ufffdcount them and fail the load past a limit; never hide them

Bigger tools have the same switches. Spark's CSV reader has multiLine off by default: a line break inside a quoted value then ends the row, and the broken rest goes where mode says (PERMISSIVE puts it in _corrupt_record). Turning multiLine on fixes the parse, but Spark can no longer split the file between tasks, so one big file becomes one slow task. BigQuery has allow_quoted_newlines, Snowflake has SKIP_BYTE_ORDER_MARK, and Spark's encoding option defaults to UTF-8.

What changed at SwiftKart

Both cases close before lunch.

Tess's file took one argument. The loader now opens every customer file with utf-8-sig, and it checks one accented name after each new source, because mojibake never raises an error.

Dana's export had one unclosed quote in a product name. You rerun the load with strict=True, find the line, and Dana fixes the exporter. From now on the loader counts rows with the parser, not lines, and compares that count with the number her database reports. She also agrees to send JSON Lines next quarter.

Flat files are behind you. The next lesson opens a file where one record holds an object and a list inside it: nested data.

In one line

A file is bytes: name the encoding, let the csv module handle the quotes, convert types as you read, and count rows with the parser, never with lines.

Interview corner

A CSV load fails with KeyError on a column you can see in the header. What do you check?

The exact header names: print reader.fieldnames and their repr. The usual causes are a byte order mark from Excel glued to the first name as \ufeff (read with encoding="utf-8-sig"), a different delimiter such as ; that leaves one giant column, stray spaces, or different capitalisation. Then I pin the encoding and dialect in code instead of relying on the machine default or a sniffer.

A 1,000,000-line CSV loads as 999,412 rows with no error. What happened?

Lines are not records. Either legitimate quoted newlines merged lines into fewer records, which is correct, or an unclosed quote put the parser in its quoted-field state and swallowed later records into one value, which is data loss. I compare the parsed record count with the source system's own count, rerun with strict=True (it raises unexpected end of data on an unclosed quote), and check the longest field. Spark with multiLine off splits quoted newlines into broken rows instead.

Why is a wrong encoding sometimes an error and sometimes silent?

UTF-8 has strict byte patterns: a cp1252 é (byte E9) is a lead byte with no valid continuation, so decoding cp1252 as UTF-8 raises UnicodeDecodeError. Every byte is valid in cp1252, so decoding UTF-8 as cp1252 never fails and produces mojibake like São Paulo. That is why I check a known accented value after onboarding a source, and count \ufffd characters if I ever use errors="replace".

Why do data pipelines prefer JSON Lines over one big JSON file?

JSON Lines holds one record per line, so a writer can append without rewriting the file and a reader can stream it in constant memory. A large file can be split between workers at line breaks, and one corrupt line can be logged and quarantined instead of making the whole file unreadable. The cost is memory per record when parsed, which lesson 2 measures.