1

I am trying to add a list to an existing csv file as a column. The code I currently have does add the list as a column to the file but to the bottom of the first column:

with open('test.csv', 'a', newline='') as csvfile:
  writer = csv.writer(csvfile, dialect='excel')
  writer.writerow([header])
  for path in StimList:
    writer.writerow([path])

Is there a way to tell the list/column being appended to the file to go in a specific column, e.g. the 5th column in the csv file like so:

column1   column2    column3    column4    column5
x         a          1          4          StimList
y         b          2          5          goes
z         c          3          6          here
  • 2
    The `a` mode of the `open()` function is used for *appending*. The `w` mode is for writing only (`w+` is reading and writing), and truncates the file (deletes contents) when the file is opened. Hence the issue you are having. Have a look at the [documentation](https://docs.python.org/3/library/functions.html#open). – S3DEV Apr 07 '22 at 09:04
  • Okay, so changing to 'a' does add the list, however it adds the new column underneath the existing rows, is there a way for me to specify where it goes. My spreadsheet is currently 4 columns wide, so I would need to add it to column 5. – Chloe Trickey Apr 07 '22 at 09:12
  • Have a think about what CSV means. Comma separated values. If you need data in column 5 for example, the line would be: `,,,,data`. – S3DEV Apr 07 '22 at 09:40

0 Answers0