【问题标题】:How to solve an EOF error when trying to open and read a binary file [duplicate]尝试打开和读取二进制文件时如何解决EOF错误[重复]
【发布时间】:2018-12-17 11:44:46
【问题描述】:

我正在学习写入和读取二进制文件,并且正在从书中复制代码以说明这是如何完成的。我把书中的两段代码放在一起来完成这个任务。在编译我的代码时,我得到一个 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()

【问题讨论】:

  • 您能否编辑您的问题以形成结构化代码
  • 您在之前的相同问题中已经有了很好的答案。

标签: python file eof


【解决方案1】:

问题是文件对象的最后一次遍历,已经结束。 在读取/写入文件时始终使用with 命令,这样您就不必担心任何此类问题。它还会自动为您关闭它

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

【讨论】:

    【解决方案2】:

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

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

    在文件末尾,这将正确地引发 EOF 异常。有两种处理方法:

    1. 不是在无限循环中加载,而是将整个数组写成一个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
      
    2. 捕获异常,然后继续。这种风格叫做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
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 2020-02-07
      • 2016-05-02
      • 2022-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多