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])
Written by Greg Roodt
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#