• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Justin Joyce

Practical tips and tutorials about software development.

  • Standing Invitation
  • Featured Posts
  • Latest
  • About

Writing CSVs in Python

Posted Feb 13, 2023 — Updated Jan 10, 2024

To write CSVs in Python, you’ll want the builtin csv module. More specifically, I usually use csv.DictWriter.

Python DictWriter

Python’s csv module has both a writer and a DictWriter class, but I’m virtually always working with dictionaries, so I always use DictWriter.

It’s pretty straightforward. You grab your data, open a file in a context manager, create a writer, and write:

from csv import DictWriter

nic_cage = {
	  "first_name": "Nicolas",
	  "last_name": "Cage",
	  "oscars": 1, # yep, he won one
	  "description": "was in National Treasure",
}

tom_hanks = 
	  "first_name": "Tom",
    "last_name": "Hanks",
	  "oscars": 2,
    "description": "IS a national treasure",
}

actors = [nic_cage, tom_hanks]

# Open a file in write mode
with open("actors.csv", "w") as outfile:
	  # The dict keys will be the csv headers
    headers = tom_hanks.keys()
    
    # create a writer
    writer = DictWriter(outfile, fieldnames=headers)

	  # write the header row
  	writer.writeheader()

	  # write the rest of the rows
    writer.writerows(actors)

That’s it!  Now you have a csv with a header row and two entries.

Important note: if any of your dicts have additional keys that aren’t in your defined set of headers, this will fail with ValueError: dict contains field not in fieldnames:

# This example will fail to write with a ValueError
from csv import DictWriter

tom_hanks = { "first_name": "Tom", "oscars": 1, "national_treasure": True }
nic_cage = { "first_name": "Nicolas", "oscars": 1 }

with open("actors.csv", "w") as outfile:
	  # tom_hanks has an additional key in his data
    # This csv will fail to write
    headers = ["first_name", "oscars"]
    
    writer = DictWriter(outfile, fieldnames=headers)
	  writer.writeheader()
    writer.writerows([tom_hanks, nic_cage])
    
# ValueError: dict contains field not in fieldnames: 'national_treasure'

However, if any of your dicts is missing a key which was defined in your headers, that piece of data will just be blank:

# This example will save fine, but with some blank data
from csv import DictWriter

tom_hanks = { "first_name": "Tom", "oscars": 2 }
meryl_streep = { "first_name": "Meryl", "last_name": "Streep" "oscars": 3 }

with open("actors.csv", "w") as outfile:
	  # tom_hanks is missing "last_name" above
    # This csv will save fine, but his last_name will be blank
    headers = ["first_name", "oscar_count", "last_name"]
    
    writer = DictWriter(outfile, fieldnames=headers)
	  writer.writeheader()
    writer.writerows([tom_hanks, meryl_streep])

Easy.

Alternative Option: Pandas

The most often-used alternative is likely pandas data_frame.to_csv(). If you do any kind of data analysis, you’re probably familiar with pandas, so I’ll just do a quick to_csv example:

import pandas as pd

# Pandas works on DataFrames, let's build a tiny one
df = pd.DataFrame(
	  [["Tom", "Hanks"], ["Meryl", "Streep"]],
    columns=["first_name", "last_name"],
)

"""
df looks like this
  first_name last_name
0        Tom     Hanks
1      Meryl    Streep
"""

# You'll probably want index=false, or your CSV will save
# the row indices 0 and 1 in an unnamed first column
df.to_csv("actors.csv", index=false)

All done. Pandas saved a CSV with headers.


Helpful Links

  • csv.DictWriter – Python official docs
  • Python Context Managers – Me!
  • Reading CSVs in Python – Also me!

Filed Under: Python

Primary Sidebar

Recent Posts

  • Every Built-In Vim Color Scheme (with screenshots)
  • Reverse a string in Python
  • Meeting Cost Calculator
  • Vim find and replace
  • What makes an effective development team

Categories

  • Arrays (5)
  • Command Line (9)
  • Dates (3)
  • Featured (7)
  • Git (7)
  • Golang (5)
  • Javascript (8)
  • Productivity (8)
  • Projects (4)
  • Python (15)
  • Regex (2)
  • Ruby (3)
  • Shell (2)
  • Thoughts (2)
  • Tips (11)
  • Tools (3)
  • Tutorials (1)
  • Vim (4)

Archives

  • July 2024 (1)
  • February 2024 (1)
  • January 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • October 2023 (4)
  • September 2023 (1)
  • August 2023 (2)
  • July 2023 (5)
  • June 2023 (3)
  • May 2023 (6)
  • April 2023 (5)
  • March 2023 (5)
  • February 2023 (10)
  • January 2023 (6)
  • December 2022 (7)

Copyright © 2025 · Contact me at justin [at] {this domain}

  • Privacy Policy