Python Forum

Full Version: reading a line of a CSV
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my .csv file could have numbers or quoted strings between the commas. this seems to be the same syntax as that found in a Python literal for a list. so what if i read in a line, .strip() it, prepend '[' to the front, append ']' to the end, and run that through exec() and verify that what is returned is a single simple list with just numbers and strings in it?
I would definitely use csv module, but if you insist on your approach, at least use ast.literal_eval()
>>>import ast
>>> line = '[1, "some text, with comma", "1,000.5"]'
>>> ast.literal_eval(line)
[1, 'some text, with comma', '1,000.5']
it looks like ast.literal_eval() is the way to go.