Python - read in the previously variable "list" from a file

I previously created listand saved it in the file 'mylist.txt'. However, when I read a line in it, that is, I cannot access each element as I like. I tried and looked for ways to fix this, but to no avail.

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

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

so if this list was equal 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

and etc.

This is useful to me, but reading on a 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 that the format is mylistbad, but it works for what I want, and it took a lot of time to create it. I tried just copying the list in python as mylist = <paste>, but the list is too long and I get a memory error.

list, , (.. )?

+5
2

ast.literal_eval. :

>>> import ast
>>> with open("file.txt", 'r') as f:
        data = ast.literal_eval(f.read())
>>> # You're done!
+13

? , Python, Python . mylist.py , mylist = [xxx].

Python script, , from .mylist import mylist, (, mylist[0] ..).

, mylist.py Python script ( __init__.py ). ( Python modules) , script, .

0

All Articles