4
votes

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?

3
replace('@|@', '|') or to something that does not contain in your string - YOU
'@|@' looks like a three character delimiter...and the code in the traceback doesn't match the code in your snippet. - martineau

3 Answers

2
votes

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

The csvfile argument to the csv.writer constructor only has to be a "file-like object". This means you could supply an instance of your own class which changes a single character into one with two or more characters (but which otherwise acts like a open output file object).

Here's what I mean:

import csv

class CSV_Translater(object):
    """ Output file-like object that translates characters. """
    def __init__(self, f, old, new):
        self.f = f
        self.old = old
        self.new = new
    def write(self, s):
        self.f.write(s.replace(self.old, self.new))
    def close(self):
        self.f.close()
    def flush(self):
        self.f.flush()

with open('in_test.csv', "rb") as ifile:
    reader = csv.reader(ifile)
    with open('out_test.csv', "wb") as ofile:
        translater = CSV_Translater(ofile, '|', '@|@')
        writer = csv.writer(translater, delimiter='|', quotechar='"',
                            quoting=csv.QUOTE_ALL)
        for row in reader:
            writer.writerow(row)
0
votes

Life is too short, just use pandas

import pandas as pd
df.to_csv('output.csv', sep='|')

By default, the delimiator is ',', that is why it is called Commasv. But by changing the sep to '|', you could simply achieve what you want.