user3655447
user3655447

Reputation: 167

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?

Upvotes: 6

Views: 11171

Answers (2)

martineau
martineau

Reputation: 123463

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)

Upvotes: 1

Marlon Abeykoon
Marlon Abeykoon

Reputation: 12465

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

Upvotes: 3

Related Questions