0

I'm using selenium and beautifulsoup to iterate through a number of webpages and sort out the results. I have that working, however I want to export the results to a CSV using this block of code:

with open('finallist.csv', mode='w') as final_list:
    stock_writer = csv.writer(final_list, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    stock_writer.writerow([ticker, element.get_text()])

The only issue is, with the result being multiple different things, this code as it stands just replaces the first line of the CSV every time a new result comes in. Is there any way I can have it write to a new line each time?

  • `mode='w'` means to create a new file, or truncate one if it exists. `mode='a'` will append to an existing file (or create a new one if it doesn't exist) – Anon Coward Feb 27 '21 at 22:07
  • 1
    Does this answer your question? [append new row to old csv file python](https://stackoverflow.com/questions/2363731/append-new-row-to-old-csv-file-python) – jidicula Feb 27 '21 at 22:11

1 Answers1

2

Per the Python documentation for the open() function, you can pass the 'a' mode to the open() function. Doing so will append any text to the end of the file, if the file already exists.

with open('finallist.csv', mode='a') as final_list:
    ...
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37