class CarRecord: # declaring a class without other methods
def init (self): # constructor
self .VehicleID = ""
self.Registration = ""
self.DateOfRegistration = None
self.EngineSize = 0
self.PurchasePrice = 0.00
import pickle # this library is required to create binary f iles
ThisCar = CarRecord()
Car = [ThisCar for i in range (100)]
CarFile = open ('Cars.DAT', 'wb') # open file for binary write
for i in range (100) : # loop for each array element
pickle.dump (Car[i], CarFile) # write a whole record to the binary file
CarFile.close() # close file
CarFile = open( 'Cars.DAT','rb') # open file for binary read
Car = [] # start with empty list
while True: # check for end of file
Car.append(pickle.load(CarFile))# append record from file to end of l i st
CarFile.close()
答案 0 :(得分:4)
这是什么?
while True: # check for end of file
try:
Car.append(pickle.load(CarFile)) # append record from file to end of l i st
except EOFError:
print('EOF!!!')
break
答案 1 :(得分:1)
您需要在循环中捕获EOFError
...
您不能永远从不包含无限数据的文件中读取数据,因此您需要为停止循环提供一种方法。
此外,绝对不需要这些循环,您可以直接存储列表,它只会加载列表。