使用pickle.load()的EOFError

时间:2015-07-29 16:55:36

标签: python python-2.7 pickle

我有以下代码:

pos = [
    [('the', 'DT'), ('rabbit', 'NN'), ... ],
    [('he', 'PRP'), ('jokes', 'VBZ'), ... ],
    ...
]
with open(filename, 'w') as f:
    pickle.dump(pos, f)

然后我要加载内容:

with open(filename, 'r') as f:
    pos = [pickle.load(f) for i in range(the_length)]

但后来我得到了这个例外:

...

  File "C:\Anaconda\lib\pickle.py", line 1378, in load
    return Unpickler(file).load()

  File "C:\Anaconda\lib\pickle.py", line 858, in load
    dispatch[key](self)

  File "C:\Anaconda\lib\pickle.py", line 880, in load_eof
    raise EOFError

EOFError

实际上,pos中的第一个列表已正确加载([('the', 'DT'), ('rabbit', 'NN'), ... ]),但异常发生在之后。 如果我打开文件,确实有问题:所有句子都存储但文件以这样的长列表结束:

aa(lp269
a(lp270
a(lp271
a(lp272
a(lp273
a(lp274
a(lp275
...
a(lp3531
a.

(我尝试使用rbwb而不是rw打开文件,但它没有解决任何问题)

1 个答案:

答案 0 :(得分:2)

如果您只有一次dump来电,则只能进行一次load来电。

with open(filename, 'r') as f:
    pos = pickle.load(f)