python - f.readline() != '0' even if reading a line containing only 0 -
i not have trouble setting variables in program var = f.readline()
function, having trouble if
statement when comes reading out of text file. trying see if 0 in text file , every time use if f.readline() == '0':
acts if not equal 0.
example of script below:
f = open("file.txt","r") myvar = f.readline() f.close if myvar == "0": print "the variable 0" raw_input("press enter continue") else: print "the variable not 0" raw_input("press enter continue")
my code come out the variable not 0
why this? , how can use if
statement readline
function?
the readline
method not remove trailing newlines lines. need manually:
myvar = f.readline().rstrip()
otherwise, myvar
equal "0\n"
, not equal "0"
.
also, forgot close file calling close
method:
f.close() # notice parenthesis
of course, using with-statement better:
with open("file.txt") f: myvar = f.readline().rstrip()
with
automatically close file when control leaves code block.
Comments
Post a Comment