问题
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:
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
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