lun
lun

Reputation: 45

Depickling from a (possibly empty) file

So I'm trying to create a file and read from it even though its empty. So the next time I run the program the file will already exist and there will be data in it.

#this should create the file
filename = open("roombooking.bin","wb")
#this should load the data into a list but since its first created it should be an empty list
monday=pickle.load(open("roombooking.bin","rb"))

this is the error i get

Traceback (most recent call last):
    monday=pickle.load(open("roombooking.bin","rb"))
  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

Upvotes: 0

Views: 8411

Answers (1)

David Robinson
David Robinson

Reputation: 78610

pickle doesn't work that way: an empty file doesn't create an empty list.

An empty list would look like this in a pickle file:

(lp0
.

If you would like to handle it so that an empty file leads to an empty list, you can use a try/except block:

try:
    monday=pickle.load(open("roombooking.bin","rb"))
except EOFError:
    monday = []

Do note, however, that "the next time you run the program", if the line filename = open("roombooking.bin","wb") occurs, it will overwrite the file.

Upvotes: 7

Related Questions