How to parse a string using a CSV parser in Python? -
i need parse string using csv parser. i've found solution in many places, doesn't work me. using python 3.4, changed 2.7.9 , still nothing...
import csv import stringio csv_file = stringio.stringio(line) csv_reader = csv.reader(csv_file) data in csv_reader: #
could please suggest me way parse string using csv parser? or how can make work?
obs: have string in csv format, fields have commas inside, that's why can't parse in standard way.
you need put double quotes around elements contain commas.
the csv format implements rfc 4180, states:
- fields containing line breaks (crlf), double quotes, , commas should enclosed in double-quotes.
so instance (run code here.):
import stringio import csv # text between double quotes treated # single element , not parsed commas line = '1,2,3,"1,2,3",4' csv_file = stringio.stringio(line) csv_reader = csv.reader(csv_file) data in csv_reader: # output: ['1', '2', '3', '1,2,3', '4'] print data
as option, can change delimiter. default csv.reader
delimiter=','
, quotechar='"'
both of these can changed depending on needs.
semicolon delimiter:
line = '1;2;3;1,2,3;4' csv_file = stringio.stringio(line) csv_reader = csv.reader(csv_file, delimiter=';') data in csv_reader: # output: ['1', '2', '3', '1,2,3', '4'] print data
vertical bar quotechar
line = '1,2,3,|1,2,3|,4' csv_file = stringio.stringio(line) csv_reader = csv.reader(csv_file, quotechar='|') data in csv_reader: # output: ['1', '2', '3', '1,2,3', '4'] print data
also, python csv
module works on python 2.6 - 3.x, shouldn't problem.
Comments
Post a Comment