[Tutor] lists and strings

Hugo González Monteverde hugonz-lists at h-lab.net
Tue Nov 8 20:13:49 CET 2005


Hi Mike,

Converting an (almost)arbitrary object into a string is what the Pickle 
module does. CPickle is faster. Take a look into into it in the docs.

Here's an example:

 >>> import cPickle
 >>> lala = [1, 2, 3, 'four', 'V']
 >>> lala
[1, 2, 3, 'four', 'V']


 >>> fileo = open('lala.pkl', 'w')
 >>> cPickle.dump(lala, fileo)
 >>> fileo.close()


 >>> fileo = open('lala.pkl', 'r')
 >>> serialized_data = fileo.read()
 >>> serialized_data
"(lp1\nI1\naI2\naI3\naS'four'\np2\naS'V'\na."

 >>> fileo.seek(0)
 >>> recovered = cPickle.load(fileo)
 >>> recovered
[1, 2, 3, 'four', 'V']
 >>>

See the docs and feel free to ask if there is some part oyu do not 
understand.

Hope it helps!

Hugo

Mike Haft wrote:
> Hello,
>      I've been working on a problem and have now sorted most of it (thanks
> to some help from the list).
> 
> All the ways of writing data to a file I know keep telling me that lists
> can't be written to the file. I'm trying to convert data from one set of
> files into files of a different format. But the easiest way to get the
> data from the first set of files is in a list(s).
> 
> So, is there any way to convert lists to strings? Or a way to write lists
> to a file?
> 
> Thanks
> 
> Mike
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list