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


Perfect! So far, we've been using the writerow() method inside a for loop to write multiple rows into a CSV file. Having a for loop gives us fine-grained control over the entire process – we can use additional variables, add new columns, and do whatever else we need.

However, when we don't need all of that, we can make our code even simpler than before. Take a look:

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'])

Instead of using a for loop, we simply use the writerows() method (instead of the writerow() method) to print the contents of our data_to_save list (note the letter "s" at the end of the method name). This method accepts a list of records and writes each of them to our CSV file. The method works with both csv.writer and csv.DictWriter.


Modify the template code so that it uses writerows() instead of a for loop.

Stuck? Here's a hint!

Take a look at the code in the explanation. You need to do the same thing in your solution.