Search code examples
pythonlistfilepickle

Pickle give Ran out of input while the file is not empty


Maybe this question has been asked many times in stackoverflow . But i can't find a solution for my code .

So , it's a very simple Def that get the data from a file called eleve.dat , then put it into a list in way to use the data from the classes inside that file .

so here is my code :

def show() :
E = []
file = open("d:\BullApp\eleve.dat", 'rb')
ch =""

while True :
    e = load(file)
    E.append(e)

While running it using a Qt5 button (it's an application for school project ) it gives me this error :

enter image description here

And i want to mention that the Binary file eleve.dat isn't empty and the other function of filling the file works perfectly .

So , i hope i find solution about this , and please don't put my Question as Duplicate because i didn't found the anwser yet .

And thanks in advance .


Solution

  • From the code it seems you have an infinite loop. Right now I can think of only 2 options best for you.
    1 - Check whether you are really getting values by printing them

    ...
    while True :
        e = load(file)
        print(e)
        E.append(e)
    

    If yes then you can terminate at the end of file like this

    ...
    while True :
        try:
            e = load(file)
            print(e)
            E.append(e)
        except EOFError:
            break
    

    2 - Which is my personal favorite to save and load data, my save_and_load.py script.

    import pickle
    def save(data, file_name):
        with open(file_name + '.dat', 'wb') as f:
            f.write(pickle.dumps(data))
    
    def load(file_name):
        with open(file_name + '.dat', 'rb') as f:
            return(pickle.loads(f.read()))
    

    You can read about pickle here. Short and simple :)