Chapter 7: More file handling

Writing to CSV files

face Josiah Wang

You can write data to a CSV file with the writer object in the csv module.

Use the .writerow() method to write a single row.

Use the .writerows() method to write multiple rows in one go.

The following code should produce a CSV file with the same content as our original students.csv from before.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import csv

header = ["name", "faculty", "department"]

data = [
        ["Alice Smith", "Science", "Chemistry"], 
        ["Ben Williams", "Eng", "EEE"],
        ["Bob Jones", "Science", "Physics"],
        ["Andrew Taylor", "Eng", "Computing"]
       ]

with open("output_students.csv", "w") as csv_file: 
    writer = csv.writer(csv_file) 
    writer.writerow(header)
    writer.writerows(data)

Writing to CSV files from a dictionary

You can also write to a CSV file from a dict rather than a list. Useful if you already have your object represented as a structured dict.

Like csv.writer above, you can write a single dictionary with .writerow() or a list of dictionaries with .writerows().

Note the new .writeheader() method in the code below! Just for the sake of it, the code also demonstrates writing a CSV separated by | instead of commas.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import csv

header = ["name", "faculty", "department"]

data = [
        {"name": "Alice Smith", "faculty": "Science", "department": "Chemistry"}, 
        {"name": "Ben Williams", "faculty": "Eng", "department": "EEE"},
        {"name": "Bob Jones", "faculty": "Science", "department": "Physics"}
       ]

extra_student = {"name": "Andrew Taylor", 
                 "faculty": "Eng", 
                 "department": "Computing"}

with open("output_students.csv", "w") as csv_file: 
    writer = csv.DictWriter(csv_file, fieldnames=header, delimiter="|") 
    writer.writeheader() 
    writer.writerows(data)
    writer.writerow(extra_student)