Good, now onto the actual CSV files. Let's start off by showing a simple example where we write data manually.
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').