Split string on commas but ignore commas within double-quotes?

XåpplI'-I0llwlg'I  - picture XåpplI'-I0llwlg'I - · Nov 9, 2011 · Viewed 34.1k times · Source

I have some input that looks like the following:

A,B,C,"D12121",E,F,G,H,"I9,I8",J,K

The comma-separated values can be in any order. I'd like to split the string on commas; however, in the case where something is inside double quotation marks, I need it to both ignore commas and strip out the quotation marks (if possible). So basically, the output would be this list of strings:

['A', 'B', 'C', 'D12121', 'E', 'F', 'G', 'H', 'I9,I8', 'J', 'K']

I've had a look at some other answers, and I'm thinking a regular expression would be best, but I'm terrible at coming up with them.

Answer

agf picture agf · Nov 9, 2011

Lasse is right; it's a comma separated value file, so you should use the csv module. A brief example:

from csv import reader

# test
infile = ['A,B,C,"D12121",E,F,G,H,"I9,I8",J,K']
# real is probably like
# infile = open('filename', 'r')
# or use 'with open(...) as infile:' and indent the rest

for line in reader(infile):
    print line
# for the test input, prints
# ['A', 'B', 'C', 'D12121', 'E', 'F', 'G', 'H', 'I9,I8', 'J', 'K']