bhavishya pawar
bhavishya pawar

Reputation: 35

EOFError in pickle.load and file not found error

elif(ch==2):
    fh=open("emp1.txt","rb+")
    fo=open("temp.txt","wb+")
    ecode=input("Enter the Ecode :")
    rec=(" ")
    try:
        while True:
            emp1= pickle.load(fh)
            if (emp1.ecode!=ecode):
                pickle.dump(emp1,fh)

    except(EOFError):
        fh.close()
        fo.close()
        os.remove("empl.txt")
        os.rename("temp.txt","emp1.txt")
        print("")

running the following code gives me this error:

Traceback (most recent call last): File "C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 78, in emp1= pickle.load(fh) EOFError

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 85, in os.remove("empl.txt") FileNotFoundError: [WinError 2] The system cannot find the file specified: 'empl.txt'

What should i do now??

Upvotes: 1

Views: 1508

Answers (2)

user8100158
user8100158

Reputation:

I would use shelve, its much easier to use and it doesn't come up with to many errors in my experience. shelve is built on pickle but it just simplify it.

here is a short tutorial

http://python.wikia.com/wiki/Shelve

Upvotes: 0

Noctis Skytower
Noctis Skytower

Reputation: 22001

You should fix your path. In the first case, you write "emp1.txt"; and in the second, you write "empl.txt". If you look carefully, you should notice that there is a difference in those two strings.

Hint: '1' != 'l'

Your code could probably be refactored as well. While it is not possible for others to test your code since it is very incomplete, the following should work in its place. You will still need to verify it works.

elif ch == 2:
    with open('emp1.txt', 'rb+') as fh, open('temp.txt', 'wb+') as fo:
        ecode = input('Enter the Ecode: ')
        while True:
            try:
                item = pickle.load(fh)
            except EOFError:
                break
            else:
                if item.ecode != ecode:
                    pickle.dump(item, fo)
    os.remove(fh.name)
    os.rename(fo.name, fh.name)
    print()

Upvotes: 1

Related Questions