Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...