write a Python 3 list to .csv

11,438

Solution 1

You can remove the \n string from your buffer like so. Also you have to add newline='' to the with statement in Python 3. See this answer for more detail.

import csv


buffer = [['a17', 'b17', 'c17', '8', 'e17', 'f17\n'],
          ['a24', 'b24', 'c24', '6', 'e24', 'f24\n'],
          ['a27', 'b27', 'c27', '9', 'e27', 'f27\n'],
          ['a18', 'b18', 'c18', '9', 'e18', 'f18\n'],
          ['a5', 'b5', 'c5', '5', 'e5', 'f5\n'],
          ['a20', 'b20', 'c20', '2', 'e20', 'f20\n'],
          ['a10', 'b10', 'c10', '1', 'e10', 'f10\n'],
          ['a3', 'b3', 'c3', '3', 'e3', 'f3\n'],
          ['a11', 'b11', 'c11', '2', 'e11', 'f11\n']]

for row_index, list in enumerate(buffer):
    for column_index, string in enumerate(list):
        buffer[row_index][column_index] = buffer[row_index][column_index].replace('\n', '')

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(buffer)

Solution 2

import csv
with open('output.csv','w') as f:
    writer = csv.writer(f)
    writer.writerows(buffer)

Note that the last entry in each of your lists has a newline, so the csvwriter is correctly quoting the string so you end up with "f17\n" (in the first list as an example) which will look strangely formatted if you are not expecting a new line.

Share:
11,438
sixD
Author by

sixD

Updated on June 04, 2022

Comments

  • sixD
    sixD almost 2 years

    I have a list that i need to write to a .csv Yes, i have done a LOT of looking around (of course i found this link which is close to the target, but misses my case) You see writerows is having all sorts of trouble with the delimiters/formatting in the .csv (the a gets separated from the 1 from the 7 etc etc)

    My list looks like this:

    buffer = [['a17', 'b17', 'c17', '8', 'e17', 'f17\n'], ['a24', 'b24', 'c24', '6', 'e24', 'f24\n'], ['a27', 'b27', 'c27', '9', 'e27', 'f27\n'], ['a18', 'b18', 'c18', '9', 'e18', 'f18\n'], ['a5', 'b5', 'c5', '5', 'e5', 'f5\n'], ['a20', 'b20', 'c20', '2', 'e20', 'f20\n'], ['a10', 'b10', 'c10', '1', 'e10', 'f10\n'], ['a3', 'b3', 'c3', '3', 'e3', 'f3\n'], ['a11', 'b11', 'c11', '2', 'e11', 'f11\n']]

    I can see its like a list of lists so i tried for eachRow in buffer: then following on with a eachRow.split(',') but no good there either. I just need to write to a .csv it should be easy right... what am i missing?

  • sixD
    sixD about 8 years
    i can't believe i was so close. you are great! That's a cool start and as you suggested the newlines are adding blank rows. So what do you suggest is the cleanest way to get rid of the \n newlines? (They just seem to be there when i read the source .csv file)
  • sixD
    sixD about 8 years
    I tried lineAsList = [i.strip() for i in a] which removes the \ns from buffer but the .csv STILL has every second row blank... any thoughts?
  • Igor
    Igor about 8 years
    I addressed your question in my answer.