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

Instruction

Good, now onto the actual CSV files. Let's start off by showing a simple example where we write data manually.

1
2
3
4
5
with open('books.csv', mode='w', newline='') as csv_file:
  csv_writer = csv.writer(csv_file)
  csv_writer.writerow(['Author', 'Title', 'Pages'])
  csv_writer.writerow(['John Smith', 'Keep holding on', '326'])
  csv_writer.writerow(['Erica Coleman', 'The beauty is the beast', '274'])

On line 1, we use the open() function. Note that we need to use the writing mode (mode='w'), and we also need to specify an empty newline character (newline=''). If we don't add the last piece, we will get double newline characters in our resulting CSV file.

On line 2, we assign a special writer object to the csv_writer variable. From now on (lines 3–5), we can use the writerow() function. As the function name suggests ("write row"), it is used to actually insert data into our CSV file. Notice how we're passing lists each time; the first time we do so, we specify the field names ('Author', 'Title', 'Pages').

Exercise

Create a file named transactions.csv, and use the writerow() function to add the following contents:

country city usd_amount payment_method
UK London 349.00 cash
France Paris 157.00 cash
Spain Barcelona 458.00 card

We've added individual pieces of information (lists: header, uk_data, france_data, and spain_data) in the Code Editor for your convenience.