我的代码中存在问题,其中unpickling每次都会导致“Ran out of input”错误。为了测试这个,我在命令提示符下运行了一些东西
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('C:/Users/Administrator/Desktop/testing/playerlist.txt', 'wb') as f:
... pickle.dump({"foo": "bar"}, f)
...
>>> with open('C:/Users/Administrator/Desktop/testing/playerlist.txt', 'rb') as f:
... print(f.read())
... print(pickle.loads(f.read()))
...
b'\x80\x03}q\x00X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02s.'
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
EOFError: Ran out of input
>>>
此代码之前适用于我,但突然没有。是否有一部分泡菜我误解了?
答案 0 :(得分:2)
print(f.read())
已读取所有输入,这意味着文件指针位于文件的末尾。所以当你以后做的时候,
print(pickle.loads(f.read()))
指针无法读取。
您可以删除第一个print(f.read())
或在f.seek(0)
之后添加print(f.read())
,将文件指针移动到文件的开头。
旁注:
就像pickle.dump(dict, f)
一样,您也可以使用pickle.load(f)
直接从文件对象加载文件,而无需使用pickle.loads(f.read())
。
答案 1 :(得分:0)
f.read()
中调用文件迭代器时, print()
会耗尽文件迭代器,因此当您在pickle.loads()
内再次调用它时,没有数据。您需要使用f.seek(0)
来回放指针,或者将其捕获到用于打印和加载的变量中。