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



