Reading — step 1 of 6
Learn
Most real-world data doesn't come to you as neatly structured Python objects. It comes as files — rows of text, values separated by commas — exported from spreadsheets, databases, APIs, and log systems. CSV (Comma-Separated Values) is the simplest and most universal tabular format. If you can parse and process CSV, you can handle data from almost anywhere.
CSV at its simplest
A CSV file looks like this:
name,age,city
Alice,30,NYC
Bob,25,SF
Carol,40,LA
The first line is the header (column names). Each following line is a record. Values are separated by commas.
Parsing CSV by hand
For simple cases, basic string operations work:
zip(fields, values) pairs each header with its value, then dict() builds the lookup. The age stays as a STRING — convert it with int() if you need arithmetic.
When manual parsing fails
Manual .split(",") works for simple CSVs but breaks on:
- Values containing commas:
"Smith, John" - Quoted strings:
"Hello, world",42 - Embedded newlines inside quoted values
- Different delimiters (tabs, semicolons)
For real-world CSV, use the csv module from the standard library:
csv.DictReader is even cleaner — uses the header row to give you dicts:
Reading from a file
The with block ensures the file is closed even if an error occurs.
Writing CSV
The newline="" is important on Windows — without it you get extra blank lines.
Type conversion
CSV values are always strings. You decide which to convert:
Common mistakes
- Using
.split(",")for production CSV — works for clean data, breaks on quoted commas. Use thecsvmodule. - Forgetting that values are strings —
"30" + 1is TypeError. Always convert numeric columns. - Forgetting
newline=""when writing on Windows — produces blank lines. - Ignoring the header — when you
.split(",")raw lines, the first row is the header, not data.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…