[Tutor] Fwd: pickle module error in source code

Alan Gauld alan.gauld at btinternet.com
Thu Jan 1 23:18:39 CET 2015

On 01/01/15 14:06, Vedhi Shreya Marwaha wrote:
> Hi! My name is Shreya Marwaha. I’m class 12th student in India. I’m using
> 2.7.5 python version [MSC v.1500 64 bit (AMD64)] on win32 as instructed by
> CBSE (central board of secondary education). I’ve been having problem in
> using pickle module.

OK, welcome.

> It keeps on showing error in the source code.   I’ve
> attached two files

If the files are short its better to just paste the contents
into your mail. Not everyone can (or is allowed to) read

: 1.   Prax.py file with error1.txt 2.   Video.py file
> with error.txt   Prax.py file is a simple problem, the first program I
> tried with pickle module.

OK, Let's stick with that initially.

The error says:

 > Traceback (most recent call last):
 >   File "C:\Users\Home\Downloads\prax.py", line 25, in <module>
 >     a=pickle.load(f)
 >   File "C:\Python27\lib\pickle.py", line 1378, in load
 >     return Unpickler(file).load()
 >   File "C:\Python27\lib\pickle.py", line 858, in load
 >     dispatch[key](self)
 >   File "C:\Python27\lib\pickle.py", line 880, in load_eof
 >     raise EOFError
 > EOFError

The relevant code is:

 > import pickle
 > a=student()
 > f=open("student.log","wb+")

In general, don;t use the + modifier with files. It usually creates more 
confusion. Just open the file for reading after you finish
writing. And try very hard not to mix reading and writing to the same file.

 > a.input()
 > pickle.dump(a,f)

Here you have written your data to the file.
The file 'cursor' is now pointing at the end of the file.

 > a=pickle.load(f)

Here you try to read from the file but the cursor is already
at the end, so you get an end of file error. To make it work
you could rewind the cursor to the beginning of the file
using seek(). But it would be much safer to simply close
the file after the dump() and then reopen the file for
reading. That avoids a whole bunch of potential complexity
and bugs just waiting to bite.

Also, consider using the 'with' structure for handling
files, it is generally safer than open/close:

with open('student.log','wb') as f:

with open('student.log','rb') as f:
     a = pickle.load()

'with' ensures the files are closed after use.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list