io.UnsupportedOpperation:阅读

问题描述

我正在编写一个程序来获取用户输入,并确定用户输入是否在列表“是”或“否”中。我想用pickle通过在代码看到新答案时询问用户它是“是”还是“否”类型的答案来教我的程序以“是”或“否”的新形式。但是,当我尝试打开包含列表的文件时出现错误。这是我的代码

import pickle
with open('yes.pkl','wb') as f:
  yes = pickle.load(f)
with open('no.pkl','wb') as f:
  no = pickle.load(f)
no = ["no","never","why should i","nope","noo","nop","n","why","no way","not in a million years"]
yes = ["yes","okay","sure","why not","fine","yah","yeah","y","yee","yesh","yess","yup","yeppers","yupperdoodle","you bet"]
def closedq(x):
  if x in no:
    print("Meany.")
    quit()
  if x in yes:
    print()
  else:
    time.sleep(1)
    print()
    print("I have not yet learned that term.")
    time.sleep(1)
    print("Is this a yes,or a no answer?")
    yesno = input()
    if yesno in yes:
      yes.append(x)
      with open('yes.pkl','wb') as f:
        pickle.dump(yes,f)
    if yesno in no:
      no.append(x)
      with open('no.pkl','wb') as f:
        pickle.dump(no,f)
    else:
      print("Meany.")
      quit()
    print("Thank you for your input. ")
    print()
print()
time.sleep(1)
print("Do you want to play a game?")
print()
play = input()
closedq(play)
print("Yay!")

我不断收到的错误如下。

Traceback (most recent call last):
  File "main.py",line 3,in <module>
    yes = pickle.load(f)
io.UnsupportedOperation: read

我在做什么错了?

解决方法

您的代码正在以只写模式打开文件,因此之后从文件读取以加载腌制的数据将失败。问题在于此行(以及no的等效行):\

with open('yes.pkl','wb') as f:

要读取文件,您需要模式'rb',而不是'wb'。在代码的更下方,当您写入文件时,可以正确打开以进行写入,但是您不希望这样做。

请注意,当文件尚不存在时,您可能需要代码中的额外逻辑。以写模式打开不存在的文件很好,您只需创建它即可。但是在读取模式下,文件必须已经存在。如果文件不存在,可能需要将yesno初始化为空列表,但是我还没有完全检查您的逻辑以了解这是否是最佳方法。