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














