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'])
csv_writer.writeheader()
csv_writer.writerows(data_to_save)
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
.