io.UnsupportedOpperation: read - python

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.

Related

Python function running truncate before user input

I'm learning python and trying to delete the contents of a life after the user input. for some reason it deletes the contents of the .txt before it asks for user input. Can't seem to work it out.
from sys import argv
import sys
script, filename = argv
def erase_contents(f):
user_input = input("> ")
if user_input == "yes":
current_file.truncate()
print("successfully deleted")
else:
sys.exit()
current_file = open(filename, "w+")
print(f"Now we are going to erase the contents of {filename}. type yes to delete.")
erase_contents(current_file)
You don't need to use truncate, because you are opening the file using w+ as the mode, which truncates the file immediately. You could use mode a instead, but really, there's no need to open the file at all until you determine that the user wants to truncate the file. You could just write
def erase_contents(fname):
user_input = input("> ")
if user_input == "yes":
with open(fname, "w"):
pass
else:
sys.exit()
print(f"Now we are going to erase the contents of {filename}. type yes to delete.")
erase_contents(filename)

How do I stop new data from python replacing old data in a csv file? [duplicate]

The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)

Basic Python Programming - writing data in a file

I am just a beginner to programming and below is the code that I have written in python to save and edit a file but every time I run the programme it erases the previous save data, so I am confused why it's happening?
filename = raw_input("Please enter the file name to open it:\n")
doc = open (filename,'w')
print doc.read
text_input = raw_input("Please enter the data you want to enter in file:\n")
if text_input == "":
print "no input closing the programme."
else :
doc.write(text_input)
doc.close()
print "Printing the file:\n"
print doc.read
cl_file = raw_input("do you want to truncate file(y/n): ")
if cl_file == "y":
doc.truncate()
else :
print "Wrong input closing notepad"
exit()
You are opening the file in write mode, which truncates the file before writing to it. Instead of using open(filename, 'w') use open(filename, 'a'). The 'a' value tells the open function to use append mode so that writes to the file are added to the end of any existing content.

Python readline() doesn't read line properly

When I have a text file and the first line is "hello", if I write
reader = open('txtfile.txt', 'r')
line = reader.readline()
print(line)
it will print "hello".
Then, when I write
input = input()
if line == input:
print('they are the same')
else:
print('they are not the same')
it says that they are not the same, even when the input is "hello". Is this a problem with my code or does readline() not allow for this?
I suggest using with open() as.. : because...
This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
Your program would become:
with open('txtfile.txt', 'r') as f:
for line in f:
answer = input('\nContent?')
if line.replace('\n','') == answer:
print('they are the same')
else:
print('they are not the same')
Also, avoid naming your variable 'input' since it will shadow the name of the build-in input().
If your file is:
hello
Hi
bye
then your first line would be 'hello\n'. replace() removes that \n before the comparison.

How to write to CSV and not overwrite past text

The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)

Categories