# pickle_example.py # # CS 1301 - Donated to the public domain Nov 2008 # # this example loads and re-saves the "tags" variable # from the tagcloud.py example program. I have removed # everything else to focus attention on just the loading # and saving of the tags dictionary to/from a file. #the dictionary of tags we load/save tags = {} #The hard way to save a dictionary. #We get all values, convert to a string, and #save them. def saveTagsHard(filename): global tags myFile = open(filename,"w") items = tags.values() for i in items: myStr = str(i) myFile.write(myStr + "\n") myFile.close() #The hard way to load tags: We read each line, #find the start and stop of the string and number #load them in, coerce the types to be right, and #store them one-by-one in the dictionary def loadTagsHard(filename): global tags myFile = open(filename,"r") line = myFile.readline() while(len(line) != 0): middle = line.find("',") word = line[2:middle] number = line[middle+2:-2] number = int( number) tags[word] = [ word, number ] line = myFile.readline() #The easy way, everything is done by Pickle! def saveTagsEasy(filename): global tags import pickle f = open(filename,"w") pickle.dump(tags,f) f.close() #The easy way, everything is done by pickle! def loadTagsEasy(filename): global tags import pickle f = open(filename,"r") tags = pickle.load(f) f.close() # this code demonstrates both the easy (using pickle) # and hard (not using pickle) ways to retrieve and save # a dictionary. #This is the hard way. #loadTagsHard("savedTagsHard.txt") #Pick this one instead to see it done the easy way! loadTagsEasy("savedTagsEasy.txt") #After we have loaded the tags, we can save them #again to demo how they were saved by the original # tagcloud program. Either the easy or hard way... #saveTagsHard("savedTagsHard.txt") #saveTagsEasy("savedTagsEasy.txt") print tags