def checkCache(cachedText):
for line in open("cache"):
if cachedText + ":" in line:
print line
open("cache").close()
else:
requestDefinition(cachedText)
This code searches each line of a file (cache) for a specific string (cachedText + “:”).
If it does not find the specific string, within the entire file it is meant to call another function (requestNewDefinition(cachedText)).
However my above code executes the function for each non-matching line.
How can one search a file for a string (cachedText + “:”), and if the string is not found anywhere in the file, execute another function?
Example Cache:
hello:world
foo:bar
your for loop is broken. you are actually checking each line of the file and executing the function for each line which does not match.
note also that calling
open("cache").close()will reopen the cache file and close it immediately, without closing the handle which was open at the beginning of the for loop.one way to perform what you need is to make the
elseclause part of theforloop. beware that an else in a for loop is tricky !.the else part of a
forloop executes at the end of the loop, only if nobreakwas called in the loop.