import pickle
class Car(object):
def __init__(self, name, price):
self.name = name
self.price = price
c = Car("benz",100000)
# 直接将对象序列化
p = pickle.dumps(c)
print(p) # b'\x80\x03c__main__\nCar\nq\ ..
# 将序列化数据还原
car = pickle.loads(p)
print(car.name) # benz
# 将对象序列化之后,写入到文件中
# pickle.dump(c,open("pickle.txt",mode="wb"))
with open("pickle.txt", "wb") as f:
pickle.dump(c, f)
# 从文件中读取对象
with open("pickle.txt", "rb") as f1:
a = pickle.load(f1)
print(a.name)
# 将多个对象写入到文件中
c1 = Car("bwm",1000)
c2 = Car("qq",2000)
lst = [c,c1,c2]
with open("pickle.txt", "wb") as f2:
pickle.dump(lst, f2)
with open("pickle.txt", "rb") as f2:
a_list = pickle.load(f2)
for duixiang in a_list:
print("-->", duixiang.name)