0Pricing
Python Academy · Lesson

Writing CSV with csv.DictWriter

Write structured data to CSV using DictReader and DictWriter.

Writing CSV with csv.DictWriter is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

csv.writer and csv.DictWriter write Python data to CSV format, handling quoting and delimiters automatically.

csv.writer Basics

csv.writer(f).writerow(row) writes a single row. writerows(rows) writes multiple.
import csv, io
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(['name', 'age'])
writer.writerow(['Alice', 30])
print(buf.getvalue())

Quoting Behavior

By default, fields with commas or quotes are automatically quoted. quoting=csv.QUOTE_ALL quotes every field.
import csv, io
buf = io.StringIO()
writer = csv.writer(buf, quoting=csv.QUOTE_ALL)
writer.writerow(['Alice', 'NYC, NY', 30])
print(buf.getvalue())

csv.DictWriter

DictWriter writes dicts as rows. Specify fieldnames. writeheader() writes the column headers.
import csv, io
buf = io.StringIO()
fields = ['name', 'age']
writer = csv.DictWriter(buf, fieldnames=fields)
writer.writeheader()
writer.writerow({'name': 'Alice', 'age': 30})
print(buf.getvalue())

writerows() for Multiple Rows

writer.writerows(list_of_rows) is more efficient than calling writerow() in a loop.
import csv, io
buf = io.StringIO()
writer = csv.DictWriter(buf, fieldnames=['x','y'])
writer.writeheader()
writer.writerows([{'x':1,'y':2},{'x':3,'y':4}])
print(buf.getvalue())

Custom Delimiter

csv.writer(f, delimiter='\t') writes tab-separated values (TSV).
import csv, io
buf = io.StringIO()
writer = csv.writer(buf, delimiter='\t')
writer.writerow(['a', 'b', 'c'])
print(repr(buf.getvalue()))

extrasaction Parameter

DictWriter(f, fieldnames, extrasaction='ignore') silently ignores extra keys in the dict instead of raising ValueError.
import csv, io
buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=['name'], extrasaction='ignore')
w.writeheader()
w.writerow({'name': 'Alice', 'extra': 'ignored'})
print(buf.getvalue())

Writing to Actual File

with open('out.csv','w',newline='',encoding='utf-8') as f: — always use newline='' and specify encoding.
import csv, tempfile, os
tmp = tempfile.mktemp(suffix='.csv')
with open(tmp, 'w', newline='') as f:
    csv.writer(f).writerows([[1,2],[3,4]])
print(open(tmp).read())
os.unlink(tmp)

Appending to CSV

open(file, 'a') appends. Be careful not to write the header again when appending.
import csv, io
buf = io.StringIO()
w = csv.writer(buf)
w.writerow(['x', 'y'])
print(buf.getvalue())

Streaming Large Writes

Write row by row — don't accumulate all rows in memory before writing.
import csv, io
buf = io.StringIO()
writer = csv.writer(buf)
for i in range(5):
    writer.writerow([i, i**2])
print(buf.getvalue())

Round-trip Test

Write data to CSV then read it back to verify correctness.
import csv, io
original = [{'name':'Alice','age':'30'},{'name':'Bob','age':'25'}]
buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=['name','age'])
w.writeheader()
w.writerows(original)
buf.seek(0)
read_back = list(csv.DictReader(buf))
print(read_back == original)

Quick Check

Which DictWriter method writes the column names as the first row?

Recap

csv.writer: writerow/writerows. DictWriter: writeheader + writerow/writerows. Always open with newline=''. Use extrasaction='ignore' for flexible dicts.

Keep Going

Keep it up! Move on to the next lesson.

Frequently asked questions

Is the “Writing CSV with csv.DictWriter” lesson free?

Yes — the full text of “Writing CSV with csv.DictWriter” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Writing CSV with csv.DictWriter”?

Write structured data to CSV using DictReader and DictWriter. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Writing CSV with csv.DictWriter” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. JSON Encoding and Decoding
  2. Handling Nested JSON Structures
  3. Reading CSV with csv.reader
  4. Writing CSV with csv.DictWriter
← Back to Python Academy