Reputation: 8382
I'm trying to split a comma seperated string where field may or may not have quotes around them.
Is there a way to define quotes to be optional?
The code below only works with quoted fields. I'm using python 2.7.11
import csv
temp = '"HELLO,WORLD",HELLO WORLD,END OF THE WORLD'
for i in csv.reader(temp):
print('#next#')
print(i)
The output is
#next
['HELLO,WORLD']
#next#
['', '']
#next#
['H']
#next#
['E']
...
Expected out is
#next
['HELLO,WORLD']
#next
['HELLO WORLD']
#next
['END OF THE WORLD']
Upvotes: 1
Views: 441
Reputation: 6915
From the csv module documentation:
csv.reader(csvfile, dialect='excel', **fmtparams)
Return a reader object which will iterate over lines in the given csvfile.
csvfile can be any object which supports the iterator protocol and
returns a string each time its next() method is called ..
So, you need to pass a list of strings to your csv.reader
call
in order to get the correct output.
temp = ['"HELLO,WORLD",HELLO WORLD,END OF THE WORLD']
Upvotes: 1