Writing CSV
Use csv.writer and csv.DictWriter to create CSV files
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Writing with csv.writer
csv.writer writes rows from lists. Call writerow() for one row or writerows() for multiple rows.
import csv
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "score"]) # header
writer.writerow(["Alice", 95])Always pass newline="" when opening a CSV file for writing. Without it, Python adds extra blank lines on Windows.
Writing with csv.DictWriter
csv.DictWriter writes rows from dictionaries. You specify the column names with fieldnames, then call writeheader() to write the header row.
headers = ["name", "score"]
with open("output.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=headers)
writer.writeheader()
writer.writerows([{"name": "Alice", "score": 95}])
Instructions
Write the same data to two CSV files — one using csv.writer, one using csv.DictWriter.
- Import
csv. - Open
scores.csvin write mode withnewline="". Create acsv.writernamedwriter. Callwriter.writerow(["name", "score"]). Callwriter.writerow(["Alice", 95]). Callwriter.writerow(["Bob", 82]). - Call
print("scores.csv written with csv.writer."). - Create
headers = ["name", "score"]androws = [{"name": "Alice", "score": 95}, {"name": "Bob", "score": 82}]. - Open
scores_dict.csvin write mode withnewline="". Create acsv.DictWriternamedwriterwithfieldnames=headers. Callwriter.writeheader(). Callwriter.writerows(rows). - Call
print("scores_dict.csv written with csv.DictWriter.").
# Step 1: Import csv # Step 2: Write scores.csv using csv.writer with header and two data rows # Step 3: Print "scores.csv written with csv.writer." # Step 4: Create headers and rows # Step 5: Write scores_dict.csv using csv.DictWriter # Step 6: Print "scores_dict.csv written with csv.DictWriter."
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding