Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give 2 characters for "delimiter" using csv module?

Tags:

python

csv

I'm trying to generate the csv with delimiter '@|@' but, I couldn't achieve through below code.

import csv
ifile  = open('test.csv', "rb")
reader = csv.reader(ifile)
ofile  = open('ttest.csv', "wb")
writer = csv.writer(ofile, delimiter='|', quotechar='"', quoting=csv.QUOTE_ALL)
for row in reader:
    writer.writerow(row)
ifile.close()
ofile.close()

While running, It has thrown below error.

Traceback (most recent call last):

File "csvfile.py", line 6, in <module>
writer = csv.writer(ofile, delimiter='@|@', quotechar='"', quoting=csv.QUOTE_ALL)
TypeError: "delimiter" must be an 1-character string

How can I achieve this?

like image 525
user3655447 Avatar asked Oct 19 '22 04:10

user3655447


1 Answers

In csv documentation they say

A one-character string used to separate fields. It defaults to ','.

So you can do this as an alternative.

csv.reader((line.replace('@|@', '|') for line in ifile), delimiter='|')

So the complete code is,

import csv
ifile  = open('test.csv', "rb")
reader = csv.reader((line.replace('@|@', '|') for line in ifile), delimiter='|')
ofile  = open('ttest.csv', "wb")
writer = csv.writer(ofile, delimiter='|', quotechar='"', quoting=csv.QUOTE_ALL)
for row in reader:
    writer.writerow(row)
ifile.close()
ofile.close()
like image 83
Marlon Abeykoon Avatar answered Oct 20 '22 23:10

Marlon Abeykoon