Reputation: 1272
I need to print each line with the word I search for
text = open("example.txt").read()
start = 0
while 1:
found = text.find("python", start)
if found == -1:
break
for line in found:
print line
start = found + 1
But I get the error:
TypeError: 'int' object is not iterable (12 line)
Upvotes: 0
Views: 97
Reputation: 12773
found
is the (integer) location of "python", you cannot iterate over it.
You probably mean something like
found = text.find("python", start)
while found != -1:
# Do something with found:
# ...
start = found + 1
found = text.find("python", start)
However, as you explicitly want to work with each line containing your word, it's best to start off with lines. Using
for line in open(filename):
or (see phihags answer)
with open(filename) as f:
for line in f:
is better than trying to handle all the text at once.
Upvotes: 1
Reputation: 287755
You cannot iterate over the integer found
. Instead, iterate over lines in the file, and use the if SUBSTRING in STRING
syntax;
with open('example.txt') as f:
for line in f:
if 'python' in line:
print(line)
Upvotes: 4