Instruction
Good job! It's time to wrap things up.
- To write data into CSV files, you can use the following template code (using lists):
with open('filename.csv', mode='w', newline='') as csv_file: csv_writer = csv.writer(csv_file) for row in data_to_save: ... - If you prefer dictionaries, you can use a
DictWriterinstead:with open('books.csv', mode='w', newline='') as csv_file: csv_writer = csv.DictWriter(csv_file, fieldnames=['field1','field2']) for row in data_to_save: ...Usecsv_writer.writeheader()to insert the header row. - Instead of a
forloop, you can use thewriterows()method to insert multiple rows. - You can specify additional parameters such as
delimiter,quotechar, andquoting. For example:csv.writer(csv_file, fieldnames=['Author','Title','Pages'], quotechar="'", quoting=csv.QUOTE_ALL)
Excellent! How about taking on a challenge now?
Exercise
Click to continue.



