Python readline() doesn't read line properly - python

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.

Related

io.UnsupportedOpperation: read

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.

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)

How do I stop the Error message coming up for every line that the searched detail isn't in?

search = input("Please enter the detail you would like to search for: ")
file = open("pupildetails.txt")
for line in file:
line = line.rstrip()
if search in line:
print(line)
else:
print("Error")
The line that prints the error message prints it for every line searched detail isn't in #I only want it to print once if none of the lines in the file contain the searched detail.
remove the lines
else:
print("Error")
BTW, the code could be rewritten as
search = input("Please enter the detail you would like to search for: ")
with open("pupildetails.txt") as file:
for line in file:
line = line.rstrip()
if search in line:
print(line)
Using with allows you to make sure the file is closed in any circumstance. Have a look at PEP 343 and this other tutorial
Note: there's no need to strip the whitespace form each line if all you do with it is check the input string is in it
I gather that you do want the error message to print if none of the file's lines contains the item. In that case, you might want to set a found flag to test after you have checked the entire file.
found = False
for line in file:
line = line.rstrip()
if search in line:
print(line)
found = True
if not found:
print("Error")
If you don't need to print every "success" line, you can make the search a one-liner:
found = any(search in line.rstrip() for line in file)

read numbers from text file python

I am trying to read a text file and return the contents of the text file. The textfile contains a matrix. When i run my code with the file it just prints the first line. My code looks right and i have searched online and cant seem to find the problem.
Code is:
def main():
matrix = "matrix1.txt"
print(readMatrix(matrix))
def readMatrix(matrix):
matrixFile = open(matrix, "r")
line = matrixFile.readline()
while line != "":
return line
line = matrixFile.readline()
matrixFile.close()
main()
while line != "":
return line # function ends
Maybe you mean
while line != "":
print line
return returns the value you pass it back to the caller and ends the function call. If you want to print each line, put the print statement instead of return.
You're misusing the return statement. When a function hits a return, control returns to the caller and does not return to the function. Thus, the most your function will do is read one line and return it, or close the file if the first line is empty.
Files in Python have a built-in iterator that will give you every line in the file, used like so:
with open(path) as f:
for line in f:
[do something]
Note the use of the with statement. It will automatically close the file when its block is exited, which makes it the preferred way to deal with reading/writing files.
So what you want to do could be something like
with open(path) as f:
for line in f:
if not line: # Equivalent to if line == ''
return
else: # This else is actually redundant, but here so the flow is clear
[do something]

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