24 lines
690 B
Python
24 lines
690 B
Python
|
import pickle
|
||
|
|
||
|
class Person:
|
||
|
def __init__(self, name, age):
|
||
|
self.name = name
|
||
|
self.age = age
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
# 对于一般的程序来说,可以使用pickle作为对象的序列化器
|
||
|
a = Person('a', 20)
|
||
|
file = open("5.文件与IO/21.test.bin", 'wb')
|
||
|
# 将序列化对象a写入file
|
||
|
pickle.dump(a, file)
|
||
|
file.close()
|
||
|
|
||
|
file = open("5.文件与IO/21.test.bin", 'rb')
|
||
|
# 从file读出序列化对象进行反序列化
|
||
|
a = pickle.load(file)
|
||
|
print(a.name, a.age)
|
||
|
|
||
|
# 值得一提的是,正在运行的线程被pickle打断后,会保存当前的状态,
|
||
|
# 当线程再次从文件中被读取,会继续之前的进度
|