'''A program that shows how data can be saved between runs of a program. We use the cPickle module to do the saving and reloading because it is easier than doing it "by hand" What this program actually does (in "Phase 2") is goofy -- you wouldn't have much use for such a program. But the way it pickles and unpickles the data is very realistic. ''' import cPickle import os.path if __name__ == "__main__": # Phase 1: Load up existing data from the last time # we ran the program (or initialize to empty if this # is the first run. if os.path.exists('data.pkl'): input_file = open('data.pkl', 'r') d = cPickle.load(input_file) input_file.close() else: d = {} # Phase 2: Do whatever the program was intended for, # which includes updating the data. print "Adding new name-major pairs ..." name = raw_input("Name (or 'quit'): ") while name != "quit": major = raw_input("Major: ") d[name] = major name = raw_input("Name: ") print "Looking up people's majors ..." name = raw_input("Name (or 'quit'): ") while name != "quit": print "%s's major is %s" % (name, d[name]) name = raw_input("Name: ") # Phase 3: Save the up-to-date version of the data # so that the next time we run the program we can # start with that data. output_file = open('data.pkl', 'w') cPickle.dump(d, output_file) output_file.close()