Spring Deals - hours only!Up to 70% off on all courses and bundles.-Close
Introduction
Writing CSV files
Summary

Instruction

Well done! Remember how we could read data from CSV files into dictionaries instead of lists? You can also use dictionaries to write data into CSV files!

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'])
  for row in data_to_save:
    csv_writer.writerow(row)

Instead of csv.writer(), we now use csv.DictWriter(). Apart from the csv file, the DictWriter also requires a list of field names. When we execute csv_writer.writerow(row), effectively taking one of the dictionaries we created in the data_to_save list and trying to write its contents into the CSV, the DictWriter checks if the fields in that dictionary are the same as those specified in the fieldnames parameter. The dictionary fields are written into the CSV file in the same order as specified in the fieldnames parameter. This means that you only need to modify the fieldnames parameter in a single place if you want to change the order of the fields; you wouldn't have to reorder the data in the data_to_save dictionary!

Exercise

Again, create a file named transactions.csv, and populate it with the data provided in the template. This time, however, you are required to add a new field at the beginning of each record. Name it 'number', and provide an integer number identifying each record (starting from 0 for the first). The end result should look like this:

0,UK,London,349.00,cash
1,France,Paris,157.00,cash
...

Stuck? Here's a hint!

Before you perform any operations on the file, you can iterate over the transactions_data list and add a new field named number to each dictionary using a counter:

counter = 0
for row in transactions_data:
  row['number'] = counter
  counter += 1

... or, if you feel like learning more, you can use enumerate():

for index, row in enumerate(transactions_data):
  row['number'] = index

The enumerate() function returns a pair (tuple) containing a count (starting from 0) and the values obtained from iterating over a given variable.