用pickle存儲讀取Python原生對象。

由於Python讀取寫入文件都必須是字符串,否則會報錯,所以使用pickle來讀取存儲Python原生對象。需要注意的是,打開文件的方式必須是二進制’b’。

>>> file=open("e:/test.txt","w")

>>> dc={"a":1,"b":12}

>>> file.write(dc)

Traceback (most recent call last):

  File "<pyshell#3>", line 1, in <module>

    file.write(dc)

TypeError: write() argument must be str, not dict

 

>>> import pickle

>>> pickle.dump(dc,file)# any object to file

>>> file.close()

>>> pickle.load(open('e:/test.txt','rb'))

{'a': 1, 'b': 2}
原文地址:https://www.cnblogs.com/MasterE/p/6644801.html