liveBook · Manning

Csv

As explained in Python Workout: 50 ten-minute exercises

The Python standard-library module that provides functionality for reading and writing comma-separated values and related delimited records.

The csv module handles delimited text records without requiring you to split and join fields manually. It supports comma-separated files, TAB-delimited output, and other delimiters. section 5.21

Writing rows

import csv with open('/tmp/stuff.csv', 'w') as f: writer = csv.writer(f) writer.writerow(range(5)) writer.writerow(['a', 'b', 'c', 'd', 'e']) Use with to flush and close the output file, then write each record as a row. section 5.21 section 5.36

A practical transformation exercise is to convert passwd-style records into a smaller TAB-delimited file:

  • Read records whose fields use colons rather than commas. section 5.21
  • Skip comment records and lines lacking a user ID field. section 5.21
  • Write the username and user ID as two output fields separated by TAB characters. section 5.21
root:*:0:0::0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1::0:0:System Services:/var/root:/usr/bin/false
# I am a comment line
_ftp:*:98:-2::0:0:FTP Daemon:/var/empty:/usr/bin/false

Inspect the source records alongside the reduced output to see delimiter conversion, field selection, and comment removal. section 5.21

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains row writing and a field-selection exercise, while deferring advanced format variation to pandas.
Examples
Uses vegetable records, writer rows, and passwd-to-TAB conversion as concrete examples.
What it assumes
Assumes familiarity with files, records, fields, and Python indexing while reinforcing line-by-line file processing.
What you can do after
Build it from scratch by selecting fields, choosing delimiters, and writing structured records to CSV files.
How it connects
Connects delimited records with text files, JSON, and pandas-based data processing.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.