I want to check if a string is in a text file. If it is, do X. If it’s not, do Y. However, this code always returns True for some reason. Can anyone see what is wrong?
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
check()
if True:
print "true"
else:
print "false"
The reason why you always got
Truehas already been given, so I’ll just offer another suggestion:If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
Another trick: you can alleviate the possible memory problems by using
mmap.mmap()to create a “string-like” object that uses the underlying file (instead of reading the whole file in memory):NOTE: in python 3, mmaps behave like
bytearrayobjects rather than strings, so the subsequence you look for withfind()has to be abytesobject rather than a string as well, eg.s.find(b'blabla'):You could also use regular expressions on
mmape.g., case-insensitive search:if re.search(br'(?i)blabla', s):