liveBook · Manning

CSV

As explained in Python Workout: 50 ten-minute exercises

CSV is a delimited text format in which records are typically represented as lines and fields are separated by a delimiter such as a comma.

CSV stores one record per line and separates fields with a delimiter, commonly a comma. It is useful when a program must exchange tabular information or move data between files and Python data structures. section 5.21 section 5.0

A practical CSV transformation follows this pattern:

  • Open the input and output files inside a with statement so both files are closed automatically. section 5.22
  • Wrap the input with csv.reader and specify its delimiter when it is not a comma. section 5.22
  • Wrap the output with csv.writer and choose the delimiter required by the output format. section 5.22
  • Iterate row by row, select or transform fields, and pass the resulting tuple or sequence to writerow. section 5.22 section 5.36
  • Handle comments, missing fields, and other malformed rows before indexing into them. section 5.22

Convert a passwd-style file to CSV

A colon-delimited passwd file can be converted into a tab-delimited output containing only usernames and user IDs: import csv with open('/etc/passwd') as passwd, open('/tmp/output.csv', 'w') as output: reader = csv.reader(passwd, delimiter=':') writer = csv.writer(output, delimiter='\t') for row in reader: if len(row) < 3: continue writer.writerow((row[0], row[2])) The reader must use ':' because the input is not comma-delimited. Rows with fewer than three fields, including the comment row, are skipped before row[2] is accessed. A startswith('#') check is another valid filtering strategy. section 5.21 section 5.22

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

View a minimal csv.writer listing that writes rows from a range and a list. section 5.21

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains records, delimiters, reader and writer configuration, row filtering, and newline differences, but defers advanced variations to pandas.
Examples
Demonstrates vegetable rows, csv.writer output, and passwd conversion from colon-delimited input to tab-delimited output.
What it assumes
Assumes familiarity with Python files, iteration, indexing, tuples, and with statements while reinforcing file-to-data transformations.
What you can do after
Apply CSV handling via Python’s csv module to read, write, filter, reformat, and selectively export delimited records.
How it connects
Connects CSV with files, delimiters, Python data structures, JSON, 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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.