Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Writing CSV files
Summary

Instruction

Very good! You may have noticed that DictWriter doesn't insert a header row by default. You have to add it manually by invoking the writeheader() method:

data_to_save = [
{'Author':'John Smith',    'Title':'Keep holding on',         'Pages':'326'},
{'Author':'Erica Coleman', 'Title':'The beauty is the beast', 'Pages':'274'}
]
with open('books.csv', mode='w', newline='') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=['Author','Title','Pages'])
csv_writer.writeheader()
for row in data_to_save:
csv_writer.writerow(row)


The header row should be inserted on the first line of a CSV file, so we invoked csv_writer.writeheader() before the for loop. This does things automatically for us, taking the list we specified in the fieldnames argument and writing it into the file.

Exercise

Create a file named capitals.csv, and populate it with the data provided in the template. Add a header row on the first line.

Stuck? Here's a hint!

Use the code from the explanation.