pythonpython-3.xcsvcsv-write-stream

Python : set delimiter as both comma and space ', '


I want to append my CSV file with a new row But the new row must be separated by a comma as well as space between them. I can only separate them with either comma or space.

The current file is:

data.csv

1,abc1,xyz1
2,abc2,xyz2
3,abc3,xyz3
4,abc4,xyz4
5,abc5,xyz5

I want it as :

data.csv

1, abc1, xyz1
2, abc2, xyz2
3, abc3, xyz3
4, abc4, xyz4
5, abc5, xyz5

My code for writing CSV:

my_new_row = [6, 'abc6', 'xyz6']
with open('data.csv', 'a', newline='') as filehandle:
    writer = csv.writer(filehandle, delimiter=',')
    writer.writerow(my_new_row)

Solution

  • The format you want to print is seem like not a stander CSV format. So you can write your own writer to print that string format.

    Common Format and MIME Type for Comma-Separated Values (CSV) Files