unpickle to python list

Tyler Eaves tyler at cg1.org
Mon Feb 3 07:30:32 EST 2003


Thomas Guettler unleashed the following on comp.lang.python:
> 
> 
> Hi!
> 
> I have a pickle which contains a flat list:
> 
> mylist=[
>   "abc",
>   "def",
>   "ghi", ...]
> 
> Is it possible to pickle this list to python syntax?
> 
> I would like to get a foo.py file which contains
> this list in python syntax.
> 
> This would make it easy to edit the list with an text
> editor.
> 
>   thomas
> 

#To Write
outf = open('somefile','w')
outf.write(str(mylist))
outf.close()

#To read
inf = open('somefile','r')
data = inf.read()
exec('mylist='+data)
inf.close()

The above code takes advantage of the fact that for dicts and lists,
str/repr returns valid python syntax.



-- 
Tyler Eaves

"There are 10^11 stars in the galaxy. That used to be a huge number. But
it's only a hundred billion. It's less than the national deficit! We used to
call them astronomical numbers. Now we should call them economical numbers."
                                                  
						  --Richard Feynman




More information about the Python-list mailing list