append to a csv file in python

To append content to an existing CSV file in Python, we can make use of the built-in csv module. The steps involved are:

  1. Open the CSV file in append mode.
  2. Create a CSV writer object.
  3. Write the data to the CSV file using the writerow() method.
main.py
import csv

# data to be added to the CSV file
data = ['John', 'Doe', '30']

# open the CSV file in append mode
with open('filename.csv', 'a') as file:

    # create a CSV writer object
    writer = csv.writer(file)

    # add the data to the CSV file
    writer.writerow(data)
278 chars
14 lines

In the above example, we open a file named "filename.csv" in append mode using the with statement, which automatically closes the file when we're done with it. We then create a CSV writer object and pass it the file. Finally, we use the writerow() method to write the data to the CSV file.

Note that we need to pass the data as a list to the writerow() method. In this example, we are adding three values: "John", "Doe", and "30".

gistlibby LogSnag