Search a file for a string, and execute a function if string not found; in python
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 (cached开发者_StackOverflow中文版Text + ":"), 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 else
clause part of the for
loop. beware that an else in a for loop is tricky !.
def checkCache(cachedText):
cache = open( "cache" )
for line in cache:
if cachedText + ":" in line:
break
else:
requestDefinition(cachedText)
cache.close()
the else part of a for
loop executes at the end of the loop, only if no break
was called in the loop.
Something like this:
def checkCache(cachedText):
for line in open("cache"):
if cachedText + ":" in line:
print line
break
else:
requestDefinition(cachedText)
Notice how the else:
is attached to the for
, not the if
. The else:
is only executed if the for
completes by exhausting the iterable, not executing the break
, which would mean that the cachedText
is not found anywhere in the file. See the Python documentation for more information.
My guess is that you want something like this. If the line is found, you should "break". "break" will end the for loop. The else statement attached to the for loop (as opposed to an if statement) will only execute if the for loop iterated through each line without ever hitting the "break" condition. You still want to close the file after you're done.
def checkCache(cachedText):
f = open("cache")
for line in f:
if cachedText + ":" in line:
print line
break
else:
requestDefinition(cachedText)
f.close()
精彩评论