Python对象持久存储
pickle模块
In [1]: d1 ={'x':11,'y':22,'z':'www.field.com'}
In [2]: print d1
{'y': 22, 'x': 11, 'z': 'www.field.com'}
In [3]: f1 = open('/field/dirt.txt','a+')
In [4]: f1.write(d1)
---------------------------------------------------------------------------
TypeError Traceback(most recent call last)
<ipython-input-4-03e18951d68d> in<module>()
----> 1 f1.write(d1)
TypeError: must be string or read-onlycharacter buffer, not dict
In [5]: import pickle
把对象dump到文件中
In [6]: pickle.dump(d1,f1)
In [7]: f1.flush()
In [8]: f1.close()
In [10]: f2=open('/field/dirt.txt','r')
pickle.load把文件装载到对象中
In [11]: d2 = pickle.load(f2)
In [12]: print d2
{'y': 22, 'x': 11, 'z': 'www.field.com'}