1、什么东西能用pickle
模块存储?
bytes
(字节串)对象, 字节数组, 以及 None
.【摘自《深入Python》】
2、示例(保存数据到PICKLE文件):
#encoding:UTF-8 import pickle #序列化 def dump_pickle(): user={} user['id']=1 user['name']='tanweijie' user['email']='[email protected]' user['sex']='boy' #with保证自动关闭文件 #设置文件模式为'wb'来以二进制写模式打开文件 with open('C:/Users/Mr_Tank_/Desktop/user.pickle','wb') as f: #dump()函数接受一个可序列化的Python数据结构 pickle.dump(user,f) print('success') #反序列化 def load_pickle(): with open('C:/Users/Mr_Tank_/Desktop/user.pickle','rb') as f: user=pickle.load(f) #user变量是一个字典 print(user)
>>> dump_pickle() success >>> load_pickle() {'id': 1, 'name': 'tanweijie', 'sex': 'boy', 'email': '[email protected]'}