Search⌘ K
AI Features

Writing a CSV File

Explore how to write CSV files in Python using the csv module's writer function and DictWriter class. Understand working with nested lists and dictionaries to organize data, specify delimiters, and efficiently write data rows. This lesson helps you gain practical skills for handling CSV outputs in your programs.

We'll cover the following...

The csv module also has two methods that you can use to write a CSV file. You can use the writer function or the DictWriter class. We’ll look at both of these as well. We will be with the writer function. Let’s look at a simple example:

Python 3.5
import csv
def csv_writer(data, path):
"""
Write data to a CSV file path
"""
with open(path, "w", newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
if __name__ == "__main__":
data = ["first_name,last_name,city".split(","),
"Tyrese,Hirthe,Strackeport".split(","),
"Jules,Dicki,Lake Nickolasville".split(","),
"Dedric,Medhurst,Stiedemannberg".split(",")
]
path = "output.csv"
csv_writer(data, path)
# You are welcome to apply the CSV Reading
# code that you learned in the previous lesson
# and read the CSV file again.
# Make sure, it outputs what you just wrote.

In the code above, we create a csv_writer function that accepts two arguments: data and path. The data is a list of lists that we create at the bottom of the script. We use a shortened version of the data from the previous example and split the strings on the comma. This returns a list. So we end up with a nested list that looks like this:

Python 3.5
[['first_name', 'last_name', 'city'],
['Tyrese', 'Hirthe', 'Strackeport'],
['Jules', 'Dicki', 'Lake Nickolasville'],
['Dedric', 'Medhurst', 'Stiedemannberg']]

The csv_writer function opens the path that we pass in and ...