我得到一个有趣的错误,而试图使用Unpickler.load(),这是源代码:

open(target, 'a').close()
scores = {};
with open(target, "rb") as file:
    unpickler = pickle.Unpickler(file);
    scores = unpickler.load();
    if not isinstance(scores, dict):
        scores = {};

下面是回溯:

Traceback (most recent call last):
File "G:\python\pendu\user_test.py", line 3, in <module>:
    save_user_points("Magix", 30);
File "G:\python\pendu\user.py", line 22, in save_user_points:
    scores = unpickler.load();
EOFError: Ran out of input

我正在读取的文件是空的。 我如何避免得到这个错误,并得到一个空变量代替?


当前回答

from os.path import getsize as size
from pickle import *
if size(target)>0:
    with open(target,'rb') as f:
        scores={i:j for i,j in enumerate(load(f))}
else: scores={}

#line 1. we importing Function 'getsize' from Library 'OS' sublibrary 'path' and we rename it with command 'as' for shorter style of writing. Important is hier that we loading only one single Func that we need and not whole Library! line 2. Same Idea, but when we dont know wich modul we will use in code at the begining, we can import all library using a command '*'. line 3. Conditional Statement... if size of your file >0 ( means obj is not an empty). 'target' is variable that schould be a bit earlier predefined. just an Example : target=(r'd:\dir1\dir.2..\YourDataFile.bin') Line 4. 'With open(target) as file:' an open construction for any file, u dont need then to use file.close(). it helps to avoid some typical Errors such as "Run out of input" or Permissions rights. 'rb' mod means 'rea binary' that u can only read(load) the data from your binary file but u cant modify/rewrite it. Line5. List comprehension method in applying to a Dictionary.. line 6. Case your datafile is empty, it will not raise an any Error msg, but return just an empty dictionary.

其他回答

如你所见,这实际上是一个自然错误。

从Unpickler对象中读取数据的典型构造如下所示。

try:
    data = unpickler.load()
except EOFError:
    data = list()  # or whatever you want

简单地引发EOFError,因为它正在读取一个空文件,它只是意味着文件结束。

注意,打开文件的模式是“a”或其他有字母的“a”也会因为覆盖而出错。

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

我会先检查文件是否为空:

import os

scores = {} # scores is an empty dict already

if os.path.getsize(target) > 0:      
    with open(target, "rb") as f:
        unpickler = pickle.Unpickler(f)
        # if file is not empty scores will be equal
        # to the value unpickled
        scores = unpickler.load()

同样,open(target, 'a').close()在你的代码中什么也不做,你不需要使用;。

if path.exists(Score_file):
      try : 
         with open(Score_file , "rb") as prev_Scr:

            return Unpickler(prev_Scr).load()

    except EOFError : 

        return dict() 

我遇到过这个错误很多次,它总是发生,因为写入文件后,我没有关闭它。如果我们不关闭文件,内容保留在缓冲区中,文件保持为空。 要将内容保存到文件中,要么关闭文件,要么超出file_object的作用域。

这就是为什么在加载时它会给出run out of input错误因为文件是空的。所以你有两个选择:

file_object.close () File_object.flush():如果你不想在程序之间关闭文件,你可以使用flush()函数,因为它会强制将内容从缓冲区移动到文件中。