How to solve an EOF error when reading a binary file

十年热恋 提交于 2019-12-20 03:13:40

问题


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()

回答1:


what about this?

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



回答2:


you need to catch EOFError in your loop…

You can't read forever from a file that does not contain infinite data, so you need to put a way for the loop to stop.

Also, there is absolutely no need to have those loops, you can directly store the list, and it will just load the list.



来源:https://stackoverflow.com/questions/53823733/how-to-solve-an-eof-error-when-reading-a-binary-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!