csv.reader() / csv.writer()
| Since: | Python 2(2000) |
|---|
Functions from the csv module for reading and writing CSV files. Use these when processing spreadsheet or tabular data.
Syntax
import csv
# Read a CSV file.
with open('data.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row) # Each row is returned as a list.
# Write to a CSV file.
with open('output.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age', 'City'])
writer.writerows([['Ayanami Rei', 14, 'Tokyo'], ['Ikari Shinji', 14, 'Tokyo']])
Function List
| Function | Description |
|---|---|
| csv.reader(f) | Takes a CSV file object and returns an iterator that yields each row as a list. |
| csv.writer(f) | Takes a CSV file object and returns a writer object for writing data in CSV format. |
| writer.writerow(row) | Writes a single row (a list) to the CSV file. |
| writer.writerows(rows) | Writes multiple rows (a list of lists) to the CSV file at once. |
| csv.DictReader(f) | Treats the first row as a header and returns an iterator that yields each row as a dictionary. |
| csv.DictWriter(f, fieldnames) | Returns a writer object for writing rows as dictionaries to a CSV file. |
| writer.writeheader() | Writes the header row (field names) when using DictWriter. |
Sample Code
csv_reader_writer.py
import csv
# Create a CSV file using csv.writer().
rows = [
['Name', 'Age', 'Org'],
['Ayanami Rei', 14, 'NERV'],
['Ikari Shinji', 14, 'NERV'],
['Soryu Asuka', 14, 'NERV'],
]
with open('users.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerows(rows)
# Read the CSV file using csv.reader().
with open('users.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.reader(f)
header = next(reader) # Read the header row.
print(f'Header: {header}')
for row in reader:
print(row) # Each row is printed as a list.
# Write rows as dictionaries using DictWriter.
users = [
{'name': 'Ayanami Rei', 'age': 14, 'org': 'NERV', 'email': 'ayanami_rei@wp-p.info'},
{'name': 'Ikari Shinji', 'age': 14, 'org': 'NERV', 'email': 'ikari_shinji@wp-p.info'},
]
with open('users2.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['name', 'age', 'org', 'email'])
writer.writeheader()
writer.writerows(users)
# Read rows as dictionaries using DictReader.
with open('users2.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['name']}, org: {row['org']}, email: {row['email']}")
# Prints something like: "Ayanami Rei, org: NERV, email: ayanami_rei@wp-p.info"
# To write a tab-separated (TSV) file, specify the delimiter.
with open('data.tsv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(['A', 'B', 'C'])
Running the code produces the following output:
python3 csv_reader_writer.py Header: ['Name', 'Age', 'Org'] ['Ayanami Rei', '14', 'NERV'] ['Ikari Shinji', '14', 'NERV'] ['Soryu Asuka', '14', 'NERV'] Ayanami Rei, org: NERV, email: ayanami_rei@wp-p.info Ikari Shinji, org: NERV, email: ikari_shinji@wp-p.info
Notes
When opening a CSV file, it is important to specify newline=''. Omitting it can cause inconsistent line ending behavior across platforms — for example, double line breaks on Windows.
Using csv.DictReader lets you access each row by column name rather than index, so you don't need to worry about column order. Because both reader and writer use an iterator-based approach, they are memory-efficient even for large datasets.
CSV files created on Windows may use the Shift-JIS (cp932) encoding. Reading them with encoding="utf-8" will result in garbled text, so make sure to match the encoding to the actual file.
Common Mistakes
Common Mistake 1: Missing newline='' causes blank lines
When writing a CSV on Windows, omitting newline='' causes double line endings, which results in blank lines between rows.
import csv
# without newline='', blank lines can appear (especially on Windows)
with open('nerv_members.csv', 'w') as f: # no newline argument
writer = csv.writer(f)
writer.writerows([['Ayanami Rei', 'NERV'], ['Ikari Shinji', 'NERV']])
The same logic can also be written as:
import csv
# specify newline=''
with open('nerv_members.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows([['Ayanami Rei', 'NERV'], ['Ikari Shinji', 'NERV']])
Common Mistake 2: Garbled text from missing encoding
When a CSV contains non-ASCII characters, always specify the encoding explicitly. To open the file in Excel without garbled text, use utf-8-sig (UTF-8 with BOM).
import csv
# no encoding specified (platform-dependent)
with open('members.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Org']) # may be garbled depending on environment
The same logic can also be written as:
import csv
# specify encoding explicitly
with open('members_utf8.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Org'])
writer.writerow(['Ayanami Rei', 'NERV'])
# For Excel: use utf-8-sig (UTF-8 with BOM)
with open('members_excel.csv', 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Org'])
writer.writerow(['Ikari Shinji', 'NERV'])
Common Mistake 3: Forgetting to skip the header row
A plain csv.reader reads the header row as the first data row. To skip the header, call next() to advance past it, or use csv.DictReader which handles the header automatically.
CSV file contents:
Name,Org,Age Ayanami Rei,NERV,14 Ikari Shinji,NERV,14
The same logic can also be written as:
import csv
# the header row is processed as data
with open('members.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row[0]) # 'Name' is printed first
The same logic can also be written as:
import csv
# skip the header with next()
with open('members.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
next(reader) # skip the header row
for row in reader:
print(row[0]) # Ayanami Rei, Ikari Shinji
# DictReader treats the header as keys automatically
with open('members.csv', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['Name'], row['Org'])
If you find any errors or copyright issues, please contact us.