Below is a simple search. It works, except for the fact that iterator is skipping the first line of the file. Inside iterator The first print statement has the correct word, but the second print statement (after the for loop) has the second line of text, not the first.
What about this for loops behavior am I missing?
"""Searches for the query inside a file
"""
def lines(the_file, query):
lines = open(the_file)
line(lines, query)
def line(lines, query):
line = lines.readline()
iterator(line, lines, word, query)
def word(line, query):
word = line.strip()
conditional(query, word)
def iterator(this, that, function, query):
print this
for this in that:
print this
function(this, query)
def conditional(this, that):
if this in that:
output(that, True)
else:
None
def output(query, result):
print query
def search(the_file, query):
lines(the_file, query)
search('c:/py/myfile.txt', 'a')
I think your problem is here:
This line:
line = lines.readline()is reading one line off the file before you start your iteration. Then in yourforloop you’re actually overwriting thethisvariable, it’s not pointing to your originallineanymore.