This is an archived version of the course. Please see the latest version of the course.

Writing to CSV files

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

You can use the writerows() method which takes multiple rows in one go.

1
2
3
4
5
6
7
8
import csv

data = [["name", "faculty", "department"], ["Davies", "Eng", "EEE"], 
        ["Smith", "Eng", "Computing"]]

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

The content of the new uni.csv should look like this:

name,faculty,department
Davies,Eng,EEE
Smith,Eng,Computing

You can also add a new (single) row to the CSV we generated using the .writerow() method.

1
2
3
4
5
6
7
8
import csv

row = ["Williams", "Eng", "EEE"]

# Note append mode "a". We are appending new items to an existing file
with open("uni.csv", "a") as csv_file:
    writer = csv.writer(csv_file) 
    writer.writerow(row)

The content of uni.csv now looks like this:

name,faculty,department
Davies,Eng,EEE
Smith,Eng,Computing
Williams,Eng,EEE

Writing to CSV files from a dictionary

You can also write to a CSV file from a dictionary.

Writing row by row (this piece of code demonstrates a CSV separated by |):

1
2
3
4
5
6
7
8
9
import csv

with open("uni.csv", "w") as csv_file: 
    fieldnames = ["name", "faculty", "dept"]

    writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter="|") 
    writer.writeheader() 
    writer.writerow({"name": "Davies", "faculty": "Eng", "dept": "EEE"}) 
    writer.writerow({"name": "Smith", "faculty": "Eng", "dept": "Computing"})

The output uni.csv file is:

name|faculty|dept
Davies|Eng|EEE
Smith|Eng|Computing

You can also dump a whole dictionary into a CSV file.

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

data = [{"name": "Davies", "faculty": "Eng", "dept": "EEE"}, 
        {"name": "Smith", "faculty": "Eng", "dept": "Comp"}
       ]

with open("uni.csv", "w") as csv_file: 
    fieldnames = ["name", "faculty", "dept"] 

    writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter="|")
    writer.writeheader() 
    writer.writerows(data)

And the output uni.csv file:

name|faculty|dept
Davies|Eng|EEE
Smith|Eng|Comp