[Tutor] A CSV field is a list of integers - how to read it as such?

Don Jennings dfjennings at gmail.com
Mon Mar 4 03:52:57 CET 2013


On Mar 3, 2013, at 9:24 PM, DoanVietTrungAtGmail wrote:

> Dear tutors
> 
> I am checking out csv as a possible data structure for my records. In each record, some fields are an integer and some are a list of integers of variable length. I use csv.DictWriter to write data. When reading out using csv.DictReader, each row is read as a string, per the csv module's standard behaviour. To get these columns as lists of integers, I can think of only a multi-step process: first, remove the brackets enclosing the string; second, split the string into a list containing substrings; third, convert  each substring into an integer. This process seems inelegant. Is there a better way to get integers and lists of integers from a csv file?

A quick search for "python list object from string representation of list" returned an idea from stackoverflow which I have adapted for integers:

>>> import ast
>>> num_string = "[1, 2, 3]"
>>> ast.literal_eval(num_string)
[1, 2, 3]


Take care,
Don



More information about the Tutor mailing list