The file-object f
is an iterator. Once you've iterated it, it's exhausted, thus your for line in f:
loop will only work for the first key. Store the lines in a list
, then it should work.
a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
lines = f.readlines() # loop the file once and store contents in list
for key in a:
for line in lines:
if key in line:
print line, key
Alternatively, you could also swap the loops, so you iterate the file only once. This could be better if the file is really big, as you won't have to load all it's contents into memory at once. Of course, this way your output could be slights different (in a different order).
a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
for line in f: # now the file is only done once...
for key in a: # ... and the key loop is done multiple times
if key in line:
print line, key
Or, as suggested by Lukas in the comments, use your original loop and 'reset' the file-iterator by calling f.seek(0)
in each iteration of the outer key
loop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…