Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - read in a previously 'list' variable from file

I previously created a list and saved it to a file 'mylist.txt'. However, when I read it in it's a string, meaning I can't access each element as I like. I have been trying and searching for ways to fix this, but to no avail.

In the text document, the list is one line and looks something like:

[(['000', '001', '002'], ('010', '011', '012')), (['100', '101', '102'], ('110', '111', '112'))]

so that if this list was equal to mylist, I could do

>>> print mylist[0]
(['000', '001', '002'], ('010', '011', '012'))
>>> print mylist[0][0]
['000', '001', '002']
>>> print mylist[0][0][2]
002

etc.

The above is useful to me, but reading in the list has the following effect:

>>>myreadlist=open("mylist.txt",'r').read()
>>>myreadlist
"[(['000', '001', '002'], ('010', '011', '012')), (['100', '101', '102'], ('110', '111', '112'))]"
>>>myreadlist[0]
'['
>>>print myreadlist[0]
[
>>>myreadlist[:15]
"[(['000', '001'"

etc. I know the format of mylist is bad, but it works for what I want and it took a very long time to generate it. I've tried just copy-pasting the list to python like mylist = <paste>, but the list is far too long and I get a memory error.

Is there a way to read the file and use it as a list so I can access each element like normal (i.e. as shown in the first print statements above)?

Thanks very much

like image 621
Dr. Jones Avatar asked Mar 24 '13 05:03

Dr. Jones


1 Answers

Pass the string to ast.literal_eval. It will safely parse the string into the appropriate structures:

>>> import ast
>>> with open("file.txt", 'r') as f:
        data = ast.literal_eval(f.read())
>>> # You're done!
like image 176
icktoofay Avatar answered Nov 14 '22 23:11

icktoofay