csv for reliable tabular text
The csv module is the reliable way to read and write CSV data in Python. It handles quoting, delimiters, and edge cases that are easy to get wrong with manual string splitting.
Why it is useful
This is fragile:
line = 'alice,"New York, NY"'
print(line.split(","))
Quoted commas break simple parsing. csv handles that correctly.
Prefer the csv module
import csv
from io import StringIO
text = 'name,city\nalice,"New York, NY"\n'
reader = csv.DictReader(StringIO(text))
for row in reader:
print(row["city"])
Output:
New York, NY
Useful patterns
csv.readerfor simple row-based readingcsv.DictReaderwhen named columns are clearercsv.writerandcsv.DictWriterfor output
Rules of thumb
- Use
csv, notsplit(","), for tabular text. - Prefer
DictReaderwhen column names matter. - Let the module handle quoting and delimiters for you.