How to solve an EOF error when trying to open and read a binary file [duplicate]

南笙酒味 提交于 2019-12-13 08:58:53

问题


I am learning to write and read from a binary file and am copying code out of a book to illustrates how this is done. I have put together two pieces of code from the book to complete this task. On compilation of my code I get an EOF error and am not sure what is causing it. Can you help? The code I am writing is listed below.

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:


The issue is the last traversal of file object, which has ended. Always use with command in case of reading/writing of a file, by this you don't have to worry about any of such issues. Also it will automatically close it for you

Car = []
with open('Cars.DAT', 'rb') as CarFile:
    Car.append(pickle.load(CarFile))



回答2:


You are reading cars from the file in an infinite loop:

while True:                         # check for end of file
    Car.append(pickle.load(CarFile))# append record from file to end of l i st

At the end of the file, this will correctly throw an EOF exception. There are two ways to handle this:

  1. Instead of loading in an infinite loop, write the whole array as a pickle, then load it back:

    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
    
  2. Catch the exception, and move on. This style is called 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
    


来源:https://stackoverflow.com/questions/53814576/how-to-solve-an-eof-error-when-trying-to-open-and-read-a-binary-file

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