EOFError:输入不足 [英] EOFError: Ran out of input

查看:84
本文介绍了EOFError:输入不足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I run the code below I get this error message "EOFError: Ran out of input" what does it mean?? How it can be corrected?? and how to output the records details on the screen.

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

推荐答案

简短回答: 最简单的解决方案是使用 pickle.dump().没有必要在一个循环中一个一个地编写所有对象.Pickle 旨在为您执行此操作.

Short answer: The simplest solution is to write the complete list to file using pickle.dump(). There's no need to write all objects one by one in a loop. Pickle is designed to do this for you.

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

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

Below is a fully working example. Some notes:

  • 我对您的 __init__ 函数进行了一些更新,使初始化代码更容易、更短.
  • 我还添加了一个 __repr__ 函数.这可用于将记录详细信息打印到屏幕上,您也曾询问过.(请注意,您也可以实现 __str__ 函数,但我选择在此示例中实现 __repr__).
  • 此代码示例使用标准 Python 编码样式 (PEP-8).
  • 此代码使用上下文管理器打开文件.这样更安全,并且无需手动关闭文件.
  • I've updated your __init__ function a bit to make the initialization code a lot easier and shorter.
  • I've also added a __repr__ function. This could be used to print the record details to screen, which you also asked. (Note that you could also implement a __str__ function, but I chose to implement __repr__ for this example).
  • This code example uses standard Python coding styles (PEP-8).
  • This code uses a context manager to open the file. This is safer and avoid the need to manually close the file.

如果您真的想手动编写对象,无论出于何种原因,有一些替代方法可以安全地做到这一点.我将在此代码示例之后解释它们:

If you really want to write the objects manually, for whatever reason, there are a few alternatives to do that safely. I'll explain them after this code example:

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)

不是立即转储列表,您还可以循环执行.以下代码片段是将汽车写入文件"的替代实现.和从文件中读取汽车".

Instead of dumping the list at once, you could also do it in a loop. The following code snippets are alternative implementations to "Write cars to file" and "Read cars from file".

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

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

At the start of the file, write the number of cars. This can be used to read the same amount of cars from the file.

    # 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:使用end"标记

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

At the end of the file, write some recognizable value, for example None. When reading this object can be used to detect the end of file.

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

这篇关于EOFError:输入不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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