pickle模块中主要有dumps()函数、loads()函数、dump() 函数、load() 函数。
#pickle.dumps(‘object‘) #序列化对象,返回值不可直接读#pickle.dump(‘object‘, f) #序列化对象到文件中#pickle.loads(‘object‘) #反序列化对象#pickle.load( f) #从文件中反序列对象,返回原先的object
import pickle obj = 123,"abcdedf",["ac",123],{"key":"value","key1":"value1"} #pickle.dumps(‘object‘) #序列化对象,返回值不可直接读 #pickle.dump(‘object‘, f) #序列化对象到文件中 #pickle.loads(‘object‘) #反序列化对象 #pickle.load(f) #从文件中反序列对象,返回原先的object r1 = pickle.dumps(obj) print(r1) r2 = pickle.loads(r1) print(r2) #f = open(‘db‘, ‘rb+‘) #‘db‘是文件名 #pickle.dump(obj, f) #f.close() with open(‘db‘, ‘rb+‘) as f: pickle.dump(obj, f) with open(‘db‘, ‘rb‘) as f: r3 = pickle.load(f) print(r3)
注意:pickle以二进制处理,所以文件打开方式应该加上b, 如‘wb‘或‘rb‘如果仅以w或r方式打开则会报错
时间: 2024-10-26 19:41:21