从(可能为空)文件中删除

时间:2014-10-21 15:24:36

标签: python pickle

所以我试图创建一个文件并从中读取,即使它是空的。因此,下次运行程序时,文件已经存在,并且其中将有数据。

#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"))

这是我得到的错误

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

1 个答案:

答案 0 :(得分:1)

pickle不起作用:空文件不会创建空列表。

一个空列表在pickle文件中看起来像这样:

(lp0
.

如果您想处理它以便空文件导致空列表,您可以使用try / except块:

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

请注意,“下次运行程序时”,如果行filename = open("roombooking.bin","wb")发生,它将覆盖文件。