I collected data in the form of list of lists and wrote the data into a text file. The data in the text file looks like
[[123231,2345,888754],[223467,85645]
Make sure that:
You can then import the list from the python file. For example say that list, my_list, is in the file mylist.py
E.g:
# This is the file mylist.py
my_list = [[123231,2345,888754],[223467,85645]]
You can then treat my_list as a python list
from mylist import my_list
for item in mylist:
print "item = <", item, ">"
This looks like valid JSON.
So you can simply do:
import json
with open(myfilename) as f:
lst = json.load(f)
To store your "list of lists" in a file, do
with open(myfilename, "w") as f:
json.dump(lst, f)
You could just pickle your data instead. To save it:
>>> import pickle
>>> p= [[123231,2345,888754],[223467,85645]]
>>> with open("data.txt", "wb") as internal_filename:
... pickle.dump(p, internal_filename)
To load it:
>>> with open("data.txt", "rb") as new_filename:
... pp = pickle.load(new_filename)
>>> pp
[[123231, 2345, 888754], [223467, 85645]]
This is also useful for much more elaborate objects.
Also you can use eval
to achieve this, but the other solutions maybe better:
# reading a list from a file
f = open('data.txt', 'r')
l = eval(f.read())
# storing a list to a file
outf = open('out','w')
outf.write(str(l))
Sometime using eval
is a bad practice. For more information check this post.