I do not have trouble setting variables in the program with the var = f.readline()
function, but I am having trouble with the if
statement when it comes to reading out of a text file. I am trying to see if a 0 is in a text file and every time I use the if f.readline() == '0':
it acts as if it does not equal 0.
Example of my script below:
f = open("file.txt","r")
myvar = f.readline()
f.close
if myvar == "0":
print "The variable is 0"
raw_input("Press enter to continue")
else:
print "The variable is not 0"
raw_input("Press enter to continue")
My code would come out as The variable is not 0
Why is this? And how can I use an if
statement with the readline
function?
The readline
method does not remove trailing newlines from lines. You need to do this manually:
myvar = f.readline().rstrip()
Otherwise, myvar
will be equal to "0\\n"
, which is not equal to "0"
.
Also, you forgot to close the file by calling the close
method:
f.close() # Notice the parenthesis
Of course, using a with-statement would be better:
with open("file.txt") as f:
myvar = f.readline().rstrip()
with
will automatically close the file when control leaves its code block.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.