The purpose of my code is to iterate over each element in an array, convert the element to a string, and return lines from another file that contain this string. My code is:
for element in myarray:
elementstring=''.join(element)
for line in myfile:
if elementstring in line:
print line
If the code is run, it will only work for the first element. Can someone explain why this is?
This is happening because when you read through the lines of a file once, you reach the end of the file and there are no lines left to read. You need to close the file and re-open it for reading for each
element.Here’s one way of doing that:
Alternatively, if this is a small enough file, you can reduce the runtime by avoiding several
reads from disk by caching the lines in the file before hand like so: