csv
reader and writer turn lines into lists of strings and back; DictReader and DictWriter do the same with dicts keyed by the header. Open every CSV file with newline='' — and never parse CSV with str.split(',').
import csv from csv import DictReader, DictWriter
Demo
import csv, io text = 'name,age\\nAda,36\\nBob,41'.replace('\\n', '\n') list(csv.reader(io.StringIO(text, newline=''), delimiter=','))
The rows end in "\r\n": that is the excel dialect's line terminator on every platform, which is why files must be opened with newline='' (otherwise Windows turns it into "\r\r\n" and you get blank rows). A field containing the delimiter, the quote character or a line break is wrapped in quotes, and a quote inside is doubled. In "split vs csv", split cannot tell a quoted comma from a separator and keeps the quote characters; csv.reader removes them. A delimiter must be exactly one character — "||" raises TypeError.
Members
Common patterns
import csv with open('people.csv', newline='', encoding='utf-8') as f: rows = list(csv.DictReader(f))
import csv with open('out.csv', 'w', newline='', encoding='utf-8') as f: w = csv.writer(f) w.writerow(['name', 'age']) w.writerows(rows)
import csv with open('data.tsv', newline='', encoding='utf-8') as f: for row in csv.reader(f, delimiter='\t'): print(row)
import csv with open('excel.csv', 'w', newline='', encoding='utf-8-sig') as f: csv.writer(f).writerows(rows)
Examples
Pitfalls
line = '"Smith, John",42' line.split(',')
import csv line = '"Smith, John",42' next(csv.reader([line]))
import csv with open('t.csv', 'w', newline='\r\n') as f: csv.writer(f).writerows([['a', 'b'], ['c', 'd']]) with open('t.csv', newline='') as f: rows = list(csv.reader(f)) rows
import csv with open('t.csv', 'w', newline='') as f: csv.writer(f).writerows([['a', 'b'], ['c', 'd']]) with open('t.csv', newline='') as f: rows = list(csv.reader(f)) rows
import csv name, age = next(csv.reader(['Ada,36'])) age + 1
import csv name, age = next(csv.reader(['Ada,36'])) int(age) + 1
When to use
- Spreadsheet exports and imports (Excel, Google Sheets, LibreOffice)
- Simple tabular data exchange between programs and databases
- Streaming large tables row by row without loading them whole
- Nested or typed data → json
- Heavy analysis, joins, type inference → pandas.read_csv
- Reading .xlsx workbooks → a library such as openpyxl (csv cannot read them)
Notes
FAQ
with open('file.csv', newline='', encoding='utf-8') as f: rows = list(csv.reader(f)) gives a list of lists of strings; csv.DictReader(f) gives one dict per row keyed by the header line.