This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

CSV - Writing

Writing to a CSV file

You can write data using the writerows() method of the csv.writer object which writes multiple rows in one go.

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.

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

with open("uni.csv", "a") as csv_file:  # Note append mode "a"
    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

You can also modify existing rows.

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

# Read existing rows
with open("uni.csv") as csv_file: 
    csv_reader = csv.reader(csv_file) 
    rows = list(csv_reader)

# Replace last row
rows[3] = row

# Save CSV with new record
with open("uni.csv", "w") as csv_file: 
    writer = csv.writer(csv_file) 
    writer.writerows(rows)

The content of uni.csv now looks like this:

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

Writing to CSV files from a dictionary

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

Writing a single row (this code demonstrates a CSV separated by |).

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.

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