Last Updated: February 25, 2016
·
10.21K
· groodt

Python trick to read single line as CSV

If you are ever in the situation where you need to parse a string using the 'csv' module, you can use this trick to parse the values. This is safer than splitting on comma in most cases.

import csv

line = 'value1,"oh look, an embedded comma",value3'
csv_reader = csv.reader( [ line ] )
fields = None
for row in csv_reader:
    fields = row

print(fields[1])

2 Responses
Add your response

import csv
from StringIO import StringIO
file_like_obj = StringIO('value1,"oh look, an embedded comma",value3')
csv_reader = csv.reader(file_like_obj)
for row in csv_reader:
    print row[1]
    break
over 1 year ago ·

Ah, that's a much nicer solution.

over 1 year ago ·