问题描述:

This is a class I created

import pickle

class CarRecord:

def __init__(self):

self.VehicleID = ""

self.Registration = ""

self.DateOfRegistration = None

self.EngineSize = 0

self.PurchasePrice = 0.00

ThisCar = CarRecord()

Car = [ThisCar for i in range(5)]

Car[0].EngineSize = 2400

Car[1].EngineSize = 2300

Car[2].EngineSize = 2200

Car[3].EngineSize = 2100

Car[4].EngineSize = 2000

I want to write these records to the binary file

CarFile = open('Cars.DAT', 'wb')

for i in range(5):

pickle.dump(Car[i], CarFile)

print(Car)

CarFile.close()

CarFile = open('Cars.DAT', 'rb')

Car = []

print("££££££££")

and append the record to he end of the list

while True:

and here I check for the end of file

Car.append(pickle.load(CarFile))

CarFile.close()

print(Car)

网友答案:

Try this code, the problem with your code is you are doing a while True, which is resulting in EOF, you need to either specify unpickling length, or handle for EOFError, as specified in the edit.

import pickle

class CarRecord:
    def __init__(self):
        self.VehicleID = ""
        self.Registration = ""
        self.DateOfRegistration = None
        self.EngineSize = 0
        self.PurchasePrice = 0.00

ThisCar = CarRecord()
Car = [ThisCar for i in range(5)]
Car[0].EngineSize = 2400
Car[1].EngineSize = 2300
Car[2].EngineSize = 2200
Car[3].EngineSize = 2100
Car[4].EngineSize = 2000

CarFile = open('Cars.DAT', 'wb')
for i in range(0,5):
    pickle.dump(Car[i], CarFile)
print(Car)

CarFile.close()
CarFile = open('Cars.DAT', 'rb')
Car = []

print("here")

for i in range(0,5):
    Car.append(pickle.load(CarFile))

CarFile.close()
print(Car)

EDIT:- I Found a better answer, which does not use hardcoded values. Reading from a file using pickle and for loop in python

I will post the answer here as well. Basically it catches EOFError and UnpicklingError so that, when file ends, it just closes, and you can use it normally as you want to

Car = []
CarFile = open('Cars.DAT', 'rb')
while 1:
    try:
        Car.append(pickle.load(CarFile))
    except (EOFError, UnpicklingError):
        break
CarFile.close()
相关阅读:
Top