7

I have a "CSV" file that uses a multi-character delimiter, so the data looks something like

field1_|#|_field2_|#|_field3_|#|_field4

Is there a way to use the Python CSV module to parse this file?

2

2 Answers 2

6

Try to replace the multichar delimiter with the singlechar one.

Somethin like this:

class DelimitedFile:
  def __init__(self, fname, mode='rb', ind=',', outd=','):
    self.f = open(fname, mode)
    self.ind = ind
    self.outd = outd

  def __iter__(self):
    return self

  def next(self):
    line = self.f.next()
    return line.replace(self.ind, self.outd)

Use it like so:

import csv

delimiter = ','

reader = csv.reader(DelimitedFile(fileName, ind='_|#|_', outd=delimiter))

for row in reader:
  print row
0
1

Python's csv module cannot process delimiters of more than one character, so the short answer to "Can the Python CSV module parse files with multi-column delimiters?" is "no". A simple test confirmed this:

reader = csv.reader(open('test.csv'), delimiter = '|#|')

Which resulted in this error:

TypeError: "delimiter" must be an 1-character string

(test.csv was a 2 row file with delimiters as shown in the code.)

Thus you'll either need to replace your delimiters with single character delimiters as @alexblum suggested, write your own parser, or find a different parser. Googling 'python csv multi-character delimiter' turned up hits to a few.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.