Round-Tripping Records Safely, CSV Versus Parquet
Write the same support-ticket records to JSON Lines, CSV and Parquet, read them back, and see exactly which values and types each format preserves.
Contentsand lesson path
On this page
- The problem
- Step 1: JSON Lines with the json module
- Step 2: CSV with the csv module
- Step 3: CSV with pandas, letting it guess
- Step 4: Giving read_csv the schema
- Step 5: Parquet keeps the schema in the file
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Handling
- JSON, CSV, Parquet and Text Encodings Concept · 15 min
- Round-Tripping Records Safely, CSV Versus Parquet Worked example · 20 min
- Schema Validation with Pydantic Models Lab · 25 min
- Tabular Cleaning with pandas Lab · 25 min
- Check: Clean a Messy Dataset Knowledge check · 6 questions
What you will learn
- Parse JSON and CSV into Python structures and serialize results back without losing data or encoding.
Prerequisites: Python Foundations
01. The problem
You are preparing support tickets for a RAG corpus. One job collects and tidies the tickets; a second job, run later, chunks and embeds them. The file between the two jobs is a contract: whatever the first job writes, the second must read back unchanged.
Call that a safe round trip: after writing and reading, every value is equal, every column has the same type, a missing value is still missing, and an empty string is still empty. The three records below are chosen to stress a format:
- account ids with leading zeros, such as
004217; - timestamps with a time zone (UTC);
- a missing priority (
None: nobody has triaged ticket 1043 yet); - text containing a comma, double quotes, a line break and Vietnamese characters;
- an empty body (
"": the customer sent only a screenshot), which means something different from a missing value.
To follow along, use Python 3.12 or later and install pip install "pandas==3.1.1" "pyarrow==26.0.1", the versions this example was tested with. Run the steps in order as one script or in one notebook, because later steps reuse names from earlier ones. The outputs shown come from those versions.
from datetime import datetime, timezone
records = [
{
"ticket_id": 1042,
"account_id": "004217",
"language": "vi",
"created_at": datetime(2024, 5, 2, 9, 15, tzinfo=timezone.utc),
"priority": 2,
"text": 'Không đăng nhập được, lỗi "E42"',
},
{
"ticket_id": 1043,
"account_id": "000981",
"language": "fr",
"created_at": datetime(2024, 5, 3, 14, 40, tzinfo=timezone.utc),
"priority": None,
"text": "Facture en double\nMerci de vérifier",
},
{
"ticket_id": 1044,
"account_id": "120554",
"language": "en",
"created_at": datetime(2024, 5, 3, 16, 5, tzinfo=timezone.utc),
"priority": 1,
"text": "",
},
]02. Step 1: JSON Lines with the json module
Start with the format closest to Python dictionaries. A first attempt fails straight away:
import json
try:
json.dumps(records[0])
except TypeError as exc:
print(exc) # Object of type datetime is not JSON serializableJSON has no date type. The default= argument of json.dumps names a function that is called for any object the encoder does not know; here it returns an ISO 8601 string. Reading back needs the reverse step, and the reader has to know which fields hold dates. datetime.fromisoformat parses the strings, including the +00:00 offset.
def encode_extra(value):
if isinstance(value, datetime):
return value.isoformat()
raise TypeError(f"Cannot serialise {type(value).__name__}")
with open("tickets.jsonl", "w", encoding="utf-8") as f:
for record in records:
print(json.dumps(record, ensure_ascii=False, default=encode_extra), file=f)
def decode(record):
record["created_at"] = datetime.fromisoformat(record["created_at"])
return record
with open("tickets.jsonl", encoding="utf-8") as f:
restored = [decode(json.loads(line)) for line in f]
print(restored == records) # TrueThe round trip is safe. Integers stay integers, None is written as null and "" as "", so the missing priority and the empty body stay different. The line break in ticket 1043 is stored as the escape \n, so the record keeps to one line, and the Vietnamese text is written as readable UTF-8 because of ensure_ascii=False.
The one weak point is the dates: the file holds strings, and the knowledge that created_at is a timestamp lives in your decode function. Keep that in mind; it is the theme of the whole lesson.
03. Step 2: CSV with the csv module
import csv
with open("tickets.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(records[0]))
writer.writeheader()
writer.writerows(records)
with open("tickets.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
print({type(value).__name__ for row in rows for value in row.values()})
print(rows[0]["account_id"], rows[0]["created_at"])
print(repr(rows[1]["priority"]), repr(rows[2]["text"])){'str'}
004217 2024-05-02 09:15:00+00:00
'' ''ticket_id,account_id,language,created_at,priority,text
1042,004217,vi,2024-05-02 09:15:00+00:00,2,"Không đăng nhập được, lỗi ""E42"""
1043,000981,fr,2024-05-03 14:40:00+00:00,,"Facture en double
Merci de vérifier"
1044,120554,en,2024-05-03 16:05:00+00:00,1,The quoting is handled correctly: the comma, the doubled quotes and the line break all survive. But look at what came back:
- Every value is a
str.1042is now"1042", and the timestamp is the text2024-05-02 09:15:00+00:00, written bystr()with a space instead of aT. Noneand""became the same empty field. Ticket 1043's missing priority and ticket 1044's empty body are now indistinguishable, and nothing in the file can tell them apart again.- The leading zeros survived, but only because the
csvmodule never guesses a type.
Every consumer of this file now has to convert each column back, and has to agree on what an empty field means.
04. Step 3: CSV with pandas, letting it guess
pandas is the usual way to move tables in and out of files, and read_csv infers a type for every column. Build a DataFrame from the same records, write it and read it back with the defaults. astype({"priority": "Int64"}) uses the nullable integer dtype (note the capital I), which can hold a missing value without turning the column into floats.
import pandas as pd
df = pd.DataFrame(records).astype({"priority": "Int64"})
df.to_csv("tickets_pd.csv", index=False)
guessed = pd.read_csv("tickets_pd.csv")
print(pd.DataFrame({"written": df.dtypes, "read back": guessed.dtypes}))
print(guessed[["account_id", "priority", "text"]]) written read back
ticket_id int64 int64
account_id str int64
language str str
created_at datetime64[us, UTC] str
priority Int64 float64
text str str
account_id priority text
0 4217 2.0 Không đăng nhập được, lỗi "E42"
1 981 NaN Facture en double\nMerci de vérifier
2 120554 1.0 NaNFour silent changes, and not one error or warning:
account_idlooked numeric, so it becameint64:004217is now4217. Joining on it against a table that keeps the zeros will match nothing.created_atcame back asstr, plain text. Sorting still looks right, but date arithmetic and time-zone handling are gone.prioritybecamefloat64. A blank field is read asNaN, which is a float, and the default integer dtype cannot hold it, so the whole column is converted.- Ticket 1044's empty body became
NaN. The CSV cannot say whether the field was empty or missing, so pandas assumes missing.
05. Step 4: Giving read_csv the schema
You can repair all four by telling read_csv what the file is supposed to contain. keep_default_na=False stops pandas treating empty fields (and strings such as NA or null) as missing; na_values then switches that back on for the one column where an empty field really does mean missing.
typed = pd.read_csv(
"tickets_pd.csv",
dtype={"account_id": str, "priority": "Int64"},
parse_dates=["created_at"],
keep_default_na=False,
na_values={"priority": [""]},
)
pd.testing.assert_frame_equal(typed, df)
print("CSV round trip matches")
print(typed[["account_id", "priority"]])
print(repr(typed.at[2, "text"]))CSV round trip matches
account_id priority
0 004217 2
1 000981 <NA>
2 120554 1
''assert_frame_equal passes, so the round trip is now safe. Notice where the fix lives, though: in reader code. The file itself still says nothing about types, so every notebook, service and colleague that opens it has to repeat these four keyword arguments exactly. The rule "empty means missing for priority but empty for text" exists only in this call. Schemas kept in reader code drift: someone adds a column, a second reader forgets dtype, and the leading zeros disappear again.
06. Step 5: Parquet keeps the schema in the file
import pyarrow.parquet as pq
df.to_parquet("tickets.parquet", index=False)
restored = pd.read_parquet("tickets.parquet")
pd.testing.assert_frame_equal(restored, df)
print("Parquet round trip matches")
print(pq.read_schema("tickets.parquet").remove_metadata())
two = pd.read_parquet("tickets.parquet", columns=["account_id", "created_at"])
print(two.dtypes)Parquet round trip matches
ticket_id: int64
account_id: large_string
language: large_string
created_at: timestamp[us, tz=UTC]
priority: int64
text: large_string
account_id str
created_at datetime64[us, UTC]
dtype: objectNo reader arguments, and the frames are identical. The schema printed by pyarrow comes from the file itself: strings stay strings, the timestamp keeps its UTC zone, and priority is an integer column that allows nulls. pandas also stores a little metadata of its own in the file, so Int64 comes back as Int64 rather than float64. The empty body is stored as an empty string and the missing priority as a null, so the difference survives.
The last call reads only two columns. Parquet keeps each column in its own chunks, so the reader skips the others, including the long text column. In a real corpus the text column usually holds most of the bytes, so a query that needs only ids and dates reads a small fraction of the file.
On pandas 2.x the printout differs slightly (text columns show object, timestamps datetime64[ns, UTC] and pyarrow reports string), but every comparison above still holds.
07. Common mistakes
08. Check your understanding
09. Apply it
Write a round-trip test for one table your project stores. Build a small fixture that contains one example of each awkward value: a zero-padded id, a timestamp with a non-UTC offset, a missing number, an empty string, a field with a comma, a quote and a line break, and some non-ASCII text.
Write it with your production writer, read it back with your production reader, and assert equality with pd.testing.assert_frame_equal (or == for a list of dicts). If the test fails, decide whether to change the format or to make the schema explicit, and keep the test in your suite so a library upgrade cannot bring the loss back.
10. Review prompt
From memory, list the four changes read_csv made when it had to guess, and say for each how Parquet avoids it. Then explain in two sentences why the typed read_csv call in step 4 is still more fragile than a Parquet file.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.