【问题标题】:EOFError: Ran out of inputEOFError:用尽输入
【发布时间】:2017-02-20 15:19:14
【问题描述】:

当我运行下面的代码时,我收到此错误消息“EOFError: Ran out of input” 这是什么意思??怎么可能改正??以及如何在屏幕上输出记录的详细信息。

import pickle # this library is required to create binary files
class CarRecord:
    def __init__(self):
      self.VehicleID = " "          
      self.Registration = " "
      self.DateOfRegistration = " "
      self.EngineSize = 0           
      self.PurchasePrice = 0.00

ThisCar = CarRecord()
Car = [ThisCar for i in range(2)] # list of 2 car records

Car[0].VehicleID = "CD333"
Car[0].Registration = "17888"
Car[0].DateOfRegistration = "18/2/2017"
Car[0].EngineSize = 2500
Car[0].PurchasePrice = 22000.00

Car[1].VehicleID = "AB123"
Car[1].Registration = "16988"
Car[1].DateOfRegistration = "19/2/2017"
Car[1].EngineSize = 2500
Car[1].PurchasePrice = 20000.00

CarFile = open ('Cars.TXT', 'wb' ) # open file for binary write
for j in range (2): # loop for each array element
    pickle.dump (Car[j], CarFile) # write a whole record to the binary file
CarFile.close() # close file

CarFile = open ('Cars.TXT','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 list
CarFile.close()

【问题讨论】:

  • 代码在while True 循环中失败,因为当它到达数据末尾时,它正试图对它没有的数据执行另一个处理
  • 尝试直接腌制/取消腌制您的Car 列表

标签: python pickle


【解决方案1】:

简答:最简单的解决方案是使用pickle.dump() 将完整列表写入文件。无需在循环中一个一个地写入所有对象。 Pickle 旨在为您做到这一点。

示例代码和替代解决方案:

下面是一个完整的示例。一些注意事项:

  • 我对您的 __init__ 函数进行了一些更新,以使初始化代码更简单、更短。
  • 我还添加了一个__repr__ 函数。这可用于将记录详细信息打印到屏幕上,您也问过。 (请注意,您也可以实现 __str__ 函数,但我在此示例中选择实现 __repr__)。
  • 此代码示例使用标准 Python 编码样式 (PEP-8)。
  • 此代码使用上下文管理器打开文件。这样更安全,无需手动关闭文件。

如果您真的想手动编写对象,无论出于何种原因,都有一些替代方法可以安全地执行此操作。我会在这个代码示例之后解释它们:

import pickle


class CarRecord:

    def __init__(self, vehicle_id, registration, registration_date, engine_size, purchase_price):
        self.vehicle_id = vehicle_id
        self.registration = registration
        self.registration_date = registration_date
        self.engine_size = engine_size
        self.purchase_price = purchase_price

    def __repr__(self):
        return "CarRecord(%r, %r, %r, %r, %r)" % (self.vehicle_id, self.registration,
                                                  self.registration_date, self.engine_size,
                                                  self.purchase_price)


def main():
    cars = [
        CarRecord("CD333", "17888", "18/2/2017", 2500, 22000.00),
        CarRecord("AB123", "16988", "19/2/2017", 2500, 20000.00),
    ]

    # Write cars to file.
    with open('Cars.TXT', 'wb') as car_file:
        pickle.dump(cars, car_file)

    # Read cars from file.
    with open('Cars.TXT', 'rb') as car_file:
        cars = pickle.load(car_file)

    # Print cars.
    for car in cars:
        print(car)


if __name__ == '__main__':
    main()

输出:

CarRecord('CD333', '17888', '18/2/2017', 2500, 22000.0)
CarRecord('AB123', '16988', '19/2/2017', 2500, 20000.0)

也可以循环执行此操作,而不是立即转储列表。以下代码 sn-ps 是“将汽车写入文件”和“从文件读取汽车”的替代实现。

备选方案 1:将对象数量写入文件

在文件的开头,写下汽车的数量。这可用于从文件中读取相同数量的汽车。

    # Write cars to file.
    with open('Cars.TXT', 'wb') as car_file:
        pickle.dump(len(cars), car_file)
        for car in cars:
            pickle.dump(car, car_file)

    # Read cars from file.
    with open('Cars.TXT', 'rb') as car_file:
        num_cars = pickle.load(car_file)
        cars = [pickle.load(car_file) for _ in range(num_cars)]

备选方案 2:使用“结束”标记

在文件末尾,写一些可识别的值,例如None。读取该对象时可用于检测文件结束。

    # Write cars to file.
    with open('Cars.TXT', 'wb') as car_file:
        for car in cars:
            pickle.dump(car, car_file)
        pickle.dump(None, car_file)

    # Read cars from file.
    with open('Cars.TXT', 'rb') as car_file:
        cars = []
        while True:
            car = pickle.load(car_file)
            if car is None:
                break
            cars.append(car)

【讨论】:

    【解决方案2】:

    你可以把while循环改成这样:

    当它收到EOFError 时,这将在输入末尾的while 循环中退出break

    while True: #check for end of file
        try:
            Car.append(pickle.load(CarFile)) # append record from file to end of list
        except EOFError:
            break
    CarFile.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2020-10-10
      • 1970-01-01
      相关资源
      最近更新 更多