[Tutor] save information in program

Daniel Ehrenberg littledanehren at yahoo.com
Sat Dec 6 22:46:51 EST 2003


Christoffer Thomsen wrote:
> I have made a few simple programs in python, but the
> problem is every 
> time I add information in any program quit and
> restart the information 
> is gone. For instance a program that saves tlf.
> numbers.
> I want to know what I should to so that the
> information is saved, and 
> if  I should wait until I have learned some more of
> python before I try 
> this.

There are two ways that information can be saved: by
"pickling" data, and by putting a few simple values in
a text file seperated by commas or newlines. Let's
take the first one: pickling. Say you have the script
below:

print 'Last time, you wrote', lasttime
thistime = raw_input('What will the variable be next
time? ')
print 'You wrote', thistime
lasttime = thistime

except you want it to save the data. What you do is
use the cPickle module. In the following replacement
script, the data is saved in data.dat.

import cPickle as p
try:
    data = file('data.dat') #opens file data.dat
except IOError:
    lasttime = '' #defaults to ''
else:
    lasttime = d.load(data) #loads stuff from data.dat
print 'Last time, you wrote', lasttime
thistime = raw_input('What will the variable be next
time? ')
print 'You wrote', thistime
datasave = file('data.dat', 'w')
d.dump(thistime, datasave)

If you want to just add to an existing thing that's
saved, you can make a list holding stuff instead of a
string.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.
http://photos.yahoo.com/



More information about the Tutor mailing list