# The first three functions manually write/read a dictionary # to a file using the format of one key/value pair per line # having form key value. # It uses looping and precise manipulation to make it all work. def saveIt(dictionary, filename="myWords.txt"): f = open(filename, "w") for pair in dictionary.items(): print(pair) key = pair[0] value = pair[1] # print(key + "\t" + value + "\n") f.write(key + "\t" + value + "\n") f.close() def loadIt(filename="myWords.txt"): f = open(filename, "r") dictionary = {} for line in f.readlines(): splitUp = line.split() dictionary[splitUp[0]] = splitUp[1] f.close() return dictionary def testIt(): dictionary = {"cat":"dog", "hi":"bye"} print(dictionary) saveIt(dictionary, "newFileName.txt") print(dictionary) dictionary = "gone!" print(dictionary) dictionary = loadIt("newFileName.txt") print(dictionary) # This second set of three functions uses almost no logic. # Instead it relies on knowing how to use the pickle module of Python 3. def saveItUsingPickleModule(dictionary, filename="testPickle.txt"): # You can look at the resultant file on your harddrive, but # it will appear to have strange characters in it. That's # because it is a binary file, and not an ascii file. import pickle f = open(filename, "wb") pickle.dump(dictionary, f) f.close() def loadItUsingPickleModule(filename="testPickle.txt"): import pickle f = open(filename, "rb") dictionary = pickle.load(f) f.close() return dictionary def testItPickled(): dictionary = {"cat":"dog", "hi":"bye"} print(dictionary) saveItUsingPickleModule(dictionary) print(dictionary) dictionary = "gone!" print(dictionary) dictionary = loadItUsingPickleModule() print(dictionary)