序列化:pickle 模塊
阿新 • • 發佈:2017-12-18
div 模塊 序列 mps 保存 狀態 with 讀取字符串 clas
序列化:將對象的狀態信息轉換為可以存儲或傳輸的形式的過程
pickle.dump(object, file) # 通過序列化的方式將一個對象保存到文件中(也可以說保存到硬盤中) pickle.load(file) # 從文件中讀取字符串,並將它重構為原來的對象 pickle.dumps(object) # 通過序列化的方式將一個對象保存到字符串變量中(也可以說保存到內存中) pickle.loads(string) # 從字符串變量中讀取字符串,並將它重構為原來的對象
In [1]: dict = {‘a‘:1, ‘b‘:2} In [2]: import pickle In [3]: with open(‘/tmp/1.pickle‘, ‘wb‘) as fd: # 將一個字典對象保存到文件中 ...: pickle.dump(dict, fd) ...: In [4]: with open(‘/tmp/1.pickle‘, ‘r‘) as fd: # 從文件中讀取字符串,並將它重構為原來的對象 ...: d = pickle.load(fd) ...: print d ...: {‘a‘: 1, ‘b‘: 2}
In [1]: dict = {‘a‘:1, ‘b‘:2} In [2]: import pickle In [3]: a1 = pickle.dumps(dict) # 將一個字典對象保存到字符串變量中 In [4]: a2 = pickle.loads(a1) # 從字符串變量中讀取字符串,並將它重構為原來的對象 In [5]: a2 Out[5]: {‘a‘: 1, ‘b‘: 2}
序列化:pickle 模塊