Python Basics: Reading and Writing CSV with Headers
CSV files often contain a header row followed by records. Python’s standard-library csv module handles quoted fields, including values that contain commas.
Use Python 3 on Linux. Run the shell commands in order in the same shell, starting in a fresh temporary directory:
cd "$(mktemp -d)"Read records by column name
Create a practice CSV file and read it with DictReader:
Save as stock.csv:
name,quantity
"Notebook, blue",2
Pencil,5Save as demo_csv_1.py:
import csv
with open("stock.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
print(f'{row["name"]}: {row["quantity"]}')Run:
python3 demo_csv_1.pyOutput:
Notebook, blue: 2
Pencil: 5DictReader uses the first row as dictionary keys. The quoted comma stays inside the notebook’s name. Splitting each line with split(",") would break that field.
Open CSV files with newline="" so the CSV module handles line endings itself.
Convert numeric fields
CSV fields are strings by default. Convert quantities before adding them:
Save as demo_csv_2.py:
import csv
with open("stock.csv", newline="", encoding="utf-8") as file:
total = sum(int(row["quantity"]) for row in csv.DictReader(file))
print(total)Run:
python3 demo_csv_2.pyOutput:
7int() raises ValueError for a blank or nonnumeric quantity. For incoming files, check the headers and validate each row before relying on it.
Write a new file
This creates summary.csv. Mode "w" overwrites that file if it already exists; keep this example in the practice directory.
Save as demo_csv_3.py:
import csv
with open("summary.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "quantity"])
writer.writeheader()
writer.writerow({"name": "Notebook, blue", "quantity": 2})
with open("summary.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
print(row["name"], row["quantity"])Run:
python3 demo_csv_3.pyOutput:
Notebook, blue 2fieldnames controls column order. The writer adds quoting where needed; you do not need to insert quotes around the notebook’s name yourself. The default format uses commas, so specify a different delimiter when your input format requires one.
Reference
Acknowledgements
This post was created with assistance from AI.