文件对象f
是一个迭代器。迭代之后,它就筋疲力尽了,因此您的for line in f:
循环仅适用于第一个键。将这些行存储在中list
,这样就可以了。
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
另外,您也可以交换循环,因此只将文件迭代一次。如果文件很大,这可能会更好,因为您不必一次将所有内容加载到内存中。当然,这样您的输出可能会略有不同(以不同的顺序)。
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
或者,如Lukas在评论中所建议的那样,使用原始循环并通过调用f.seek(0)
外部key
循环的每次迭代来“重置”文件迭代器。