Module 15 · Python Standard Libraries — topic 9 of 13
csv
The csv module beyond the basics: other delimiters, quoting styles, writing to strings with io.StringIO, line terminators, and validating rows while reading.
Learning objectives
- Read files with other delimiters
- Control quoting when writing
- Validate and convert rows while reading
Definition
csv reads and writes delimited text. Options such as delimiter, quotechar, quoting and lineterminator adapt it to the many CSV variants produced by spreadsheets and other programs.
Introduction
'CSV' files come in many flavours: semicolons in Europe, tabs in exports, quotes everywhere or nowhere. The csv module's options handle them all.
Why it matters
Data imports fail on small format differences. Configuring the reader correctly and validating rows avoids corrupted results.
Detailed explanation
delimiter=";" or "\t" reads semicolon- or tab-separated files.
Quoting: QUOTE_MINIMAL (default, only when needed), QUOTE_ALL, QUOTE_NONNUMERIC (quote strings, and convert unquoted fields to float when reading) and QUOTE_NONE.
The writer ends lines with \r\n by default; lineterminator="\n" changes that.
io.StringIO acts like a text file in memory, handy for building CSV text or parsing a string.
Values are strings. Convert and validate each row, collecting errors with line numbers instead of stopping at the first bad row.
csv.Sniffer can guess the dialect of unknown files, but explicit options are more reliable.
Spreadsheet programs often add a byte-order mark at the start of UTF-8 CSV files, which makes the first header look like "\ufeffname". Opening such files with encoding="utf-8-sig" removes the mark automatically.
For very large files, process rows one at a time inside the loop instead of collecting them all in a list first; the reader itself is lazy and uses little memory.
Syntax
- delimiter for other separators.
- quoting controls quotes.
- StringIO for in-memory CSV.
Code examples
Semicolon-separated data
['name', 'city'] ['Asha', 'Pune'] ['Ravi', 'Delhi']
Quoting styles
"item","price" "pen",20.5
More examples
Validating rows from a tab-separated export
2 ["line 3: bad amount 'abc'"] 1450
Step-by-step explanation
- The header is line 1, so data rows are numbered from 2 to match what a user sees in an editor.
- Invalid amounts are recorded with their line number and skipped.
- The total includes only the valid rows.
Expected output
Running “Validating rows from a tab-separated export” prints exactly:
Practical applications
- Importing bank exports with semicolons.
- Generating CSV text for an HTTP download.
Best practices
- Specify the delimiter explicitly.
- Validate and convert every row.
- Report errors with line numbers.
Common mistakes
Assuming commas
Avoid
Prefer
Every row would come back as one field.
Important notes
- csv.register_dialect saves a set of options under a name for reuse.
Key takeaways
- delimiter and quoting adapt to CSV variants.
- StringIO builds CSV in memory.
- Validate rows as you read them.
Try it yourself
- 1Convert a semicolon-separated file into a comma-separated one.
- 2Read a CSV and report rows with missing values.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
14 questions cover the “Python Standard Libraries” module. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhy call random.seed(42) before generating numbers in a test?
- ModerateWhat is printed?