我正在学习读写二进制文件,并从一本书中复制代码以说明如何完成此操作。我整理了本书中的两段代码以完成此任务。在编译我的代码时,出现EOF错误,并且不确定是什么原因引起的。你能帮我吗?我正在编写的代码在下面列出。
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 :(得分:0)
问题是文件对象的最后一次遍历已结束。
在读取/写入文件时始终使用with
命令,因此您不必担心任何此类问题。还会自动为您关闭
Car = []
with open('Cars.DAT', 'rb') as CarFile:
Car.append(pickle.load(CarFile))
答案 1 :(得分:0)
您正在无限循环地从文件中读取汽车:
while True: # check for end of file
Car.append(pickle.load(CarFile))# append record from file to end of l i st
在文件末尾,这将正确引发EOF异常。有两种处理方法:
不是将整个数组加载为无限循环,而是将整个数组写为pickle,然后将其加载回去:
CarFile = open ('Cars.DAT', 'wb') # open file for binary write
pickle.dump(Car, CarFile) # write the whole list to a binary file
...
CarFile = open('Cars.DAT', 'rb') # open file for binary read
Car = pickle.load(CarFile) # load whole list from file
捕获异常,然后继续。这种样式称为EAFP。
Car = [] # start with empty list
while True: # check for end of file
try:
Car.append(pickle.load(CarFile)) # append record from file to end of list
except EOFError:
break # break out of loop