I am making a program that gets a user input and determines if the user input is in either list 'yes' or 'no'. I want to use pickle to teach my program new forms of yes or no answers by asking the user when the code sees a new answer whether or not it is a 'yes' or 'no' type answer. I have an error, however, when I try to open the file that contains the lists. Here is my code:
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!")
The error I keep receiving is as follows.
Traceback (most recent call last):
File "main.py", line 3, in <module>
yes = pickle.load(f)
io.UnsupportedOperation: read
What am I doing wrong here?
Your code is opening the file in write-only mode, so reading from it to load the pickled data fails afterward. The issue is with this line (and the equivalent one for no
):\
with open('yes.pkl', 'wb') as f:
For reading a file, you want mode 'rb'
, instead of 'wb'
. Further down in the code, when you're writing to the file, you do correctly open for writing, but you don't want that up top.
Note that you may need extra logic in your code for when the file doesn't exist yet. Opening a non-existent file in write mode is fine, you just create it. But in read mode, the file needs to exist already. Initializing yes
and no
to empty lists might be what you want if the file doesn't exist yet, but I haven't fully examined your logic to know if that's the best approach.