[Tutor] File Input of "Objects"

Wolfram Kraus kraus at hagen-partner.de
Thu Jun 2 08:34:23 CEST 2005


Chuck Allison wrote:
> Hello tutor,
> 
>   I notice that with 'print >> f' one can print the string
>   representation of objects to a file. Is there a corresponding input
>   facility that parses through a file creating objects? I can't find
>   one. In the meantime, I did this:
> 
> 
>>>>f = open('out.dat','w')
>>>>print >> f, 1, 2
>>>>f.close()
>>>>s = open('out.dat').read()
>>>>x,y = tuple(map(eval,s.split()[:2]))
>>>>x,y
> 
> (1, 2)  
> 
> This is just what came to mind without thought. Is there a Pythonic
> way to read formatted objects? Thanks.
> 
If you want to save objects to a file and reread them later, the best 
solution is pickle:
http://www.python.org/doc/2.4.1/tut/node9.html#SECTION009220000000000000000
and
http://www.python.org/doc/2.4.1/lib/module-pickle.html

HTH,
Wolfram



More information about the Tutor mailing list