python parse prints only first line from list -
i have list 'a',where need print matching letters of list line of text file 'hello.txt'.but prints first word list , line instead of list , lines
a=['comp','graphics','card','part'] open('hello.txt', 'r') f: key in a: line in f: if key in line: print line, key
it results as:
comp , python comp
desired output:
comp , python comp graphics , pixel graphics micro sd card card python part part
please me desires output.answers willbe appreciated!
the file-object f
iterator. once you've iterated it, it's exhausted, for line in f:
loop work first key. store lines in list
, should work.
a=['comp','graphics','card','part'] open('hello.txt', 'r') f: lines = f.readlines() # loop file once , store contents in list key in a: line in lines: if key in line: print line, key
alternatively, swap loops, iterate file once. better if file big, won't have load it's contents memory @ once. of course, way output slights different (in different order).
a=['comp','graphics','card','part'] open('hello.txt', 'r') f: line in f: # file done once... key in a: # ... , key loop done multiple times if key in line: print line, key
or, suggested lukas in comments, use original loop , 'reset' file-iterator calling f.seek(0)
in each iteration of outer key
loop.
Comments
Post a Comment