我得到一个有趣的错误,而试图使用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
我正在读取的文件是空的。
我如何避免得到这个错误,并得到一个空变量代替?
这里的大多数答案都涉及了如何管理EOFError异常,如果您不确定pickle对象是否为空,这非常方便。
然而,如果您惊讶于pickle文件是空的,这可能是因为您通过'wb'或其他可能覆盖该文件的模式打开了文件名。
例如:
filename = 'cd.pkl'
with open(filename, 'wb') as f:
classification_dict = pickle.load(f)
这将覆盖pickle文件。你可能在使用之前错误地这样做了:
...
open(filename, 'rb') as f:
然后得到EOFError,因为前面的代码块覆盖了cd.pkl文件。
当在Jupyter或在控制台(Spyder)中工作时,我通常在读写代码上编写包装器,然后调用包装器。这避免了常见的读写错误,如果要多次读取同一个文件,还节省了一些时间
pickle文件很可能是空的。
如果要复制和粘贴代码,那么覆盖pickle文件非常容易。
例如,下面写一个pickle文件:
pickle.dump(df,open('df.p','wb'))
如果你复制这段代码重新打开它,但忘记把'wb'改为'rb',那么你会覆盖文件:
df=pickle.load(open('df.p','wb'))
正确的语法是
df=pickle.load(open('df.p','rb'))
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.