How to Read and Write CSV Files in Python
To read a CSV file in Python, open it with newline="" and loop over csv.reader(f), which gives each row as a list of strings. To write one, use csv.writer(f) with writerow() or writerows(). For columns by name, use csv.DictReader and csv.DictWriter. With default settings, values come back as text, so convert numbers with float() or int() before doing math.
On this page▾
- Why not just split on commas?
- How do you write CSV files in Python?
- How do you read a CSV file in Python?
- Why are CSV numbers read as strings?
- Reading by column name with DictReader
- Writing dictionaries with DictWriter
- A checklist for CSV work
- Frequently asked questions
- What does Python csv.DictReader do?
- How do I write CSV files in Python?
- Check the delimiter and encoding before importing
- What happens if a row has missing or extra columns?
- Does writing None preserve it as a special value?
The built-in csv module handles quoted commas that a plain string split cannot. The examples use a small sales file. If open(), file modes and with are new to you, start with how to read and write text files in Python.
| Task | Python CSV API | Result |
|---|---|---|
| Read by position | csv.reader(f) |
A list for each row |
| Read by header | csv.DictReader(f) |
A dictionary for each data row |
| Write sequences | csv.writer(f) |
writerow() or writerows() |
| Write dictionaries | csv.DictWriter(f, fieldnames=...) |
Explicit column order; writeheader() writes names |
Why not just split on commas?
This sales-file row has a comma inside the customer name:
line = '2026-10-02,"Smith, Jo",75.50'
print(line.split(","))
['2026-10-02', '"Smith', ' Jo"', '75.50']
You wanted three fields and got four. CSV files protect commas inside values by wrapping the value in quotes, and a plain split() does not understand that rule. The csv module does.
Opening, reading and closing plain text files is covered in How to Read and Write Text Files in Python.
How do you write CSV files in Python?
Save and run this script to create the sample file:
import csv
rows = [
["date", "customer", "amount"],
["2026-10-01", "Northwind", "120.00"],
["2026-10-02", "Smith, Jo", "75.50"],
["2026-10-02", "Blue Cafe", "42.25"],
]
with open("sales.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
The file it creates looks like this:
date,customer,amount
2026-10-01,Northwind,120.00
2026-10-02,"Smith, Jo",75.50
2026-10-02,Blue Cafe,42.25
The writer added quotes around "Smith, Jo" automatically and left the other values alone. writerows() writes a whole list of rows. For one row at a time, use writerow().
Use newline="" in open(). The open() documentation says newline controls how line endings are handled, and with newline="" no translation takes place on write. The csv documentation says a file passed to the module should be opened this way. Its footnote explains why: without it, newlines inside quoted fields are not interpreted correctly, and on platforms that use \r\n line endings an extra \r is added on write. It should always be safe to specify newline="", because the csv module does its own newline handling.
How do you read a CSV file in Python?
import csv
with open("sales.csv", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)
['date', 'customer', 'amount']
['2026-10-01', 'Northwind', '120.00']
['2026-10-02', 'Smith, Jo', '75.50']
['2026-10-02', 'Blue Cafe', '42.25']
Each row is a list, and "Smith, Jo" correctly stays in one piece.
Why are CSV numbers read as strings?
The amounts are strings: '120.00' has quotes around it. By default, each row is returned as a list of strings and no automatic data type conversion is performed. Options such as QUOTE_NONNUMERIC can change that behavior. Trying to add them up directly fails:
import csv
total = 0
with open("sales.csv", newline="") as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
total += row[2]
print(total)
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
Convert with float() before doing math:
import csv
total = 0
with open("sales.csv", newline="") as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
total += float(row[2])
print(header)
print(f"{total:.2f}")
['date', 'customer', 'amount']
237.75
next(reader) pulls off the first row, the header, so the loop only sees data rows. 120.00 + 75.50 + 42.25 = 237.75.
Reading by column name with DictReader
Counting column positions gets fragile when a file has many columns or someone reorders them. csv.DictReader turns each row into a dictionary. The documentation explains that if you do not supply field names, the values in the first row are used as the keys and that row is left out of the results.
import csv
with open("sales.csv", newline="") as f:
for row in csv.DictReader(f):
print(row["customer"], row["amount"])
Northwind 120.00
Smith, Jo 75.50
Blue Cafe 42.25
row["amount"] is easier to read than row[2], and it keeps working if a new column is added in front.
Writing dictionaries with DictWriter
csv.DictWriter goes the other way. Unlike DictReader, the documentation notes that its fieldnames argument is required, because it sets the column order. This script copies only the sales of 50 or more into a new file:
import csv
big = []
with open("sales.csv", newline="") as f:
for row in csv.DictReader(f):
if float(row["amount"]) >= 50:
big.append({"customer": row["customer"], "amount": row["amount"]})
with open("big_sales.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["customer", "amount"])
writer.writeheader()
writer.writerows(big)
The new file contains:
customer,amount
Northwind,120.00
"Smith, Jo",75.50
writeheader() writes the column names as the first row. If you pass a dictionary with a key that is not in fieldnames, the documentation says DictWriter raises a ValueError by default. Running it with an extra "note" key printed:
ValueError: dict contains fields not in fieldnames: 'note'
That error is protective: it stops data from silently going missing. To ignore extra keys, use extrasaction="ignore".
A checklist for CSV work
import csvand open files withnewline="".- Use
next(reader)orDictReaderto deal with the header row. - Convert numbers with
int()orfloat()before calculating. - Prefer
DictReaderandDictWriterwhen files have more than a few columns.
Frequently asked questions
What does Python csv.DictReader do?
It returns each row as a dictionary. When fieldnames is omitted, it takes the keys from the first row and excludes that header row from the data.
How do I write CSV files in Python?
Open the output file in write mode with newline="" and pass it to csv.writer(). Use writerow() for one row or writerows() for an iterable of rows.
Check the delimiter and encoding before importing
The Python 3 CSV API accepts a one-character delimiter. A semicolon-separated file needs that delimiter, not a manual split. The encoding belongs to open(), while the field separator belongs to the CSV reader:
with open("sales.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f, delimiter=";"):
print(row)
This example assumes the input is UTF-8 and semicolon-separated. The delimiter defaults to a comma.
What happens if a row has missing or extra columns?
For DictReader, extra values go into a list under the restkey key, which defaults to None. Missing values are filled with restval, also None by default. That differs from DictWriter's default error for unexpected dictionary keys: reading a row is not the same as validating its shape.
Does writing None preserve it as a special value?
No. csv.writer writes None as an empty string. That transformation is not reversible, so reading the file again cannot distinguish it from an originally empty string without an additional convention in your data.
Sources
About this guide
Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.
AboutEditorial standardsCorrectionsReport an error
Edit history
- Updated
- Updated
- Updated
- Updated
- Published