576i
576i

Reputation: 8382

Python: How to split a string with csv reader that has optional quotes

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

Answers (1)

taras
taras

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

Related Questions