这是我创建的课程
import pickle
class CarRecord:
def __init__(self):
self.VehicleID = ""
self.Registration = ""
self.DateOfRegistration = None
self.EngineSize = 0
self.PurchasePrice = 0.00
ThisCar = CarRecord()
Car = [ThisCar for i in range(5)]
Car[0].EngineSize = 2400
Car[1].EngineSize = 2300
Car[2].EngineSize = 2200
Car[3].EngineSize = 2100
Car[4].EngineSize = 2000
我想将这些记录写入二进制文件
CarFile = open('Cars.DAT', 'wb')
for i in range(5):
pickle.dump(Car[i], CarFile)
print(Car)
CarFile.close()
CarFile = open('Cars.DAT', 'rb')
Car = []
print("££££££££")
并将记录追加到列表的末尾
while True:
在这里我检查文件的结尾
Car.append(pickle.load(CarFile))
CarFile.close()
print(Car)
答案 0 :(得分:3)
试试这段代码,代码的问题是你做了一段时间的True,导致EOF,你需要指定unpickling长度,或者为编辑中指定的EOFError处理。
import pickle
class CarRecord:
def __init__(self):
self.VehicleID = ""
self.Registration = ""
self.DateOfRegistration = None
self.EngineSize = 0
self.PurchasePrice = 0.00
ThisCar = CarRecord()
Car = [ThisCar for i in range(5)]
Car[0].EngineSize = 2400
Car[1].EngineSize = 2300
Car[2].EngineSize = 2200
Car[3].EngineSize = 2100
Car[4].EngineSize = 2000
CarFile = open('Cars.DAT', 'wb')
for i in range(0,5):
pickle.dump(Car[i], CarFile)
print(Car)
CarFile.close()
CarFile = open('Cars.DAT', 'rb')
Car = []
print("here")
for i in range(0,5):
Car.append(pickle.load(CarFile))
CarFile.close()
print(Car)
编辑: - 我找到了一个更好的答案,它不使用硬编码值。 Reading from a file using pickle and for loop in python
我也会在这里发布答案。基本上它会捕获EOFError和UnpicklingError,这样当文件结束时,它就会关闭,你可以按照你想要的那样正常使用它
Car = []
CarFile = open('Cars.DAT', 'rb')
while 1:
try:
Car.append(pickle.load(CarFile))
except (EOFError, UnpicklingError):
break
CarFile.close()