liveBook · Manning

Csv

As explained in Python Workout, Second Edition

The csv module is Python's standard-library module for reading and writing comma-separated and other delimiter-separated tabular data.

Use Python’s standard-library csv module to read and write tabular text records whose fields are separated by commas, tabs, colons, or other delimiters. section 6.18

A practical workflow is to:

  • Open the input and output files, preferably with with, and process the input one line at a time. section 6.30
  • Configure the delimiter to match the data: commas for ordinary CSV, tabs for TSV-style output, or colons for passwd-style records. section 6.18
  • Use csv readers and writers rather than manually splitting and joining fields. section 6.18

Converting passwd records

A passwd_to_csv function reads colon-separated records, skips comment lines or records without a user ID, and writes each username with its user ID separated by tabs. The input may contain comments and fields beyond the selected indexes. section 6.18

import csv

with open('/tmp/stuff.csv', 'w') as f:
    o = csv.writer(f)             #1
    o.writerow(range(5))             #2
    o.writerow(['a', 'b', 'c', 'd', 'e'])      #3

A compact writer example shows creating a csv.writer and emitting rows from Python values. section 6.18

How Python Workout, Second Edition covers it

How deep it goes
Explains delimiters, readers, writers, linewise processing, and a passwd transformation while stopping short of deeper parser internals.
Examples
Uses vegetable records, writer rows, and Unix passwd records transformed into tab-separated username and user-ID output.
What it assumes
Assumes basic Python file handling and indexing while reinforcing linewise iteration, context managers, and structured text conversion.
What you can do after
Apply it via Python’s csv module to transform delimiter-separated files into selected output fields.
How it connects
Connects CSV with text files, file iteration, JSON, delimiters, and Python data structures.

Also explained in

Compare how 4 books explain csv →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.