liveBook · Manning

CSV

As explained in Python Workout, Second Edition

A CSV file is a text file that represents tabular records with fields separated by delimiters, commonly commas.

CSV represents tabular records as text: one record per line, with fields separated by a delimiter. Commas are traditional, but tabs, colons, or other character sequences also work. section 6.18

Use Python’s csv module instead of manually splitting lines when reading or writing CSV. Open files with with, then choose the delimiter that matches the data. section 6.18 section 6.30

Convert passwd-style data

Implement passwd_to_csv(input_filename, output_filename): read colon-separated records, skip comment records without a user ID, and write username plus user ID separated by TAB characters. 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 minimal writer demonstrates creating a csv.writer and emitting rows with writerow. section 6.18

Practice extensions include:

  • Let users choose output fields and delimiters. section 6.21
  • Write dictionaries, random-number rows, and summary calculations. section 6.21

How Python Workout, Second Edition covers it

How deep it goes
Explains delimiters, csv.writer, filtering, and selected fields, but does not develop advanced CSV variations.
Examples
Uses vegetable records, passwd-style records, TAB-delimited output, dictionaries, and random integers.
What it assumes
Assumes familiarity with opening files, iterating over lines, and selecting fields from records.
What you can do after
Build CSV transformations with Python’s csv module, including delimiter selection, field filtering, and row writing.
How it connects
Connects CSV with text files, delimiters, the csv module, passwd-style files, and pandas.

Also explained in

Compare how 15 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.