pickle
是一个序列化模块。
对象序列化与文件对象
import pickle
file_name = './demo.txt'
x,y,z = 'hello1', 100, 200
with open(file_name, 'wb') as fp:
# 对象序列化到文件对象
pickle.dump(x, fp)
pickle.dump(y, fp)
pickle.dump(z, fp)
with open(file_name, 'rb') as f:
for _ in range(3):
# 对象反序列化,从文件读取数据
a = pickle.load(f)
print(f"读取到的内容:{a}, 类型为:{type(a)}")
输出打印结果如下:
读取到的内容:hello1, 类型为:<class 'str'>
读取到的内容:100, 类型为:<class 'int'>
读取到的内容:200, 类型为:<class 'int'>
对象序列化与bytes对象
import pickle
dict1 = {'aa': 11, 'bb': 22}
dict_data = pickle.dumps(dict1)
print(dict_data)
data = pickle.loads(dict_data)
print(data, type(data))
list1 = [1, 2, 3]
list_data = pickle.dumps(list1)
print(list_data)
data_list = pickle.loads(list_data)
print(data_list, type(data_list))
输出打印结果如下:
b'x80x03}qx00(Xx02x00x00x00aaqx01Kx0bXx02x00x00x00bbqx02Kx16u.'
{'aa': 11, 'bb': 22} <class 'dict'>
b'x80x03]qx00(Kx01Kx02Kx03e.'
[1, 2, 3] <class 'list'>