[출처 : http://www.saltycrane.com/blog/2008/01/saving-python-dict-to-file-using-pickle/]
Here is an example using
Results:
Here is an example using
pickle
which writes a Python dict to a file and reads it back again:import pickle
# write python dict to a file
mydict = {'a': 1, 'b': 2, 'c': 3}
output = open('myfile.pkl', 'wb')
pickle.dump(mydict, output)
output.close()
# read python dict back from the file
pkl_file = open('myfile.pkl', 'rb')
mydict2 = pickle.load(pkl_file)
pkl_file.close()
print mydict
print mydict2
Results:
{'a': 1, 'c': 3, 'b': 2} {'a': 1, 'c': 3, 'b': 2}
Maybe you want something like this?
import pickle
# write python dict to a file
mydict = {'a': 1, 'b': 2, 'c': 3}
output = open('myfile.pkl', 'wb')
pickle.dump(mydict, output)
output.close()
print mydict
# read python dict back from the file
pkl_file = open('myfile.pkl', 'rb')
mydict = pickle.load(pkl_file)
pkl_file.close()
print mydict
# update dict and write to the file again
mydict.update({'d': 4})
output = open('myfile.pkl', 'wb')
pickle.dump(mydict, output)
output.close()
# read python dict back from the file
pkl_file = open('myfile.pkl', 'rb')
mydict = pickle.load(pkl_file)
pkl_file.close()
print mydict
Results:
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 3, 'b': 2, 'd': 4}