how to read list from file

Roy Smith roy at panix.com
Sat Oct 5 21:34:00 EDT 2013


In article <fbc6e512-88fa-4de0-80d3-6757fcc52af4 at googlegroups.com>,
 Harvey Greenberg <hjgreenberg at gmail.com> wrote:

> I am looping as for L in file.readlines(), where file is csv.
> 
> L is a list of 3 items, eg, [{'a':1, 'b':2}, [1,2,3], 10] Note that the first 
> item is a dir and 2nd is a list, so parsing with split doesn't work.  Is 
> there a way to convert L, which is a string, to the list of 3 items I want?

I hate to recommend it (since it's bad practice for a number of 
legitimate reasons), but passing your string to eval() will get you what 
you want.

It's also very close to being valid JSON syntax, the only difference 
being the use of single instead of double quotes.  You might want to 
just turn it into JSON by substituting the right kind of quotes.

json.loads("[{'a':1, 'b':2}, [1,2,3], 10]".replace("'", '"'))
[{u'a': 1, u'b': 2}, [1, 2, 3], 10]



More information about the Python-list mailing list