import pickle
"""将对象转化为硬盘能识别的bytes的过程被称为序列号。pickle可以把任意python类型的数据转化为字节"""
print(pickle.dumps("中"))
print(type(pickle.dumps("中")))
print(pickle.dumps([4, 2, 1]))
print(type(pickle.dumps([4, 2, 1])))
b'x80x03Xx03x00x00x00xe4xb8xadqx00.'
<class 'bytes'>
b'x80x03]qx00(Kx04Kx02Kx01e.'
<class 'bytes'>
import pickle
"""将bytes转化为python对象的过程被称为反序列化"""
print(pickle.loads(b'x80x03Xx03x00x00x00xe4xb8xadqx00.'))
print(type(pickle.loads(b'x80x03Xx03x00x00x00xe4xb8xadqx00.')))
print(pickle.loads(b'x80x03]qx00(Kx04Kx02Kx01e.'))
print(type(pickle.loads(b'x80x03]qx00(Kx04Kx02Kx01e.')))
中
<class 'str'>
[4, 2, 1]
<class 'list'>
import pickle
print(pickle.dumps([4, 2, 1])) # 序列化
print(pickle.loads(b'x80x03]qx00(Kx04Kx02Kx01e.')) # 反序列化
b'x80x03]qx00(Kx04Kx02Kx01e.'
[4, 2, 1]
import pickle
"""将序列化后的bytes写入文件"""
pickle.dump("中", open("str2.dat", "wb"))
pickle.dump([4, 2, 1], open("lst.dat", "wb"))
import pickle
"""读取文件中的bytes"""
print(pickle.load(open("str2.dat", "rb")))
print(pickle.load(open("lst.dat", "rb")))
中
[4, 2, 1]
import pickle
pickle.dump([1, 2, 3], open("lst.bytes", "wb")) # 把任意类型的数据转化为字节,并保存到文件中
print(pickle.load(open("lst.bytes", "rb"))) # 从文件中读取字节数据,并转换为对应的python数据
[1, 2, 3]
"""只有字符串类型的转化为字节使用encode"""
print([4, 2, 1].encode("utf-8"))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-134-f5e7d7f2d811> in <module>()
1 """只有字符串类型的转化为字节使用encode"""
----> 2 print([4, 2, 1].encode("utf-8"))
AttributeError: 'list' object has no attribute 'encode'
import pickle
"""encode和pickle.dumps的对字符串进行转字节结果是不一样的。"""
print(pickle.dumps("中"))
print("中".encode("utf-8"))
b'x80x03Xx03x00x00x00xe4xb8xadqx00.'
b'xe4xb8xad'