尝试打开和读取二进制文件时如何解决EOF错误 [英] How to solve an EOF error when trying to open and read a binary file

查看:77
本文介绍了尝试打开和读取二进制文件时如何解决EOF错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习读写二进制文件,并从一本书中复制代码以说明如何完成此工作。我整理了本书中的两段代码以完成此任务。在编译我的代码时,出现EOF错误,并且不确定是什么原因引起的。你能帮我吗?我正在编写的代码在下面列出。

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


推荐答案

您正在无限循环地从文件中读取汽车:

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

在文件末尾,这将正确引发EOF异常。有两种方法可以解决此问题:

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


  1. 不是将其加载为无限循环,而是将整个数组写为pickle,然后重新加载:

  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


  • 捕获异常,然后继续。这种样式称为 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
    


  • 这篇关于尝试打开和读取二进制文件时如何解决EOF错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆