Reputation: 91
Currently, this code is giving me all lines from searchfile
once. But with my newbie understanding, it should print out all lines from searchfile
for every infile
line!
searchfile = open('.\sometext.txt', 'r')
infile = open('.\somefile', 'r')
for line1 in infile:
for line2 in searchfile:
print line2
searchfile.close()
infile.close()
I tried to use searchfile.readlines()
to create a list to print all infile
lines for all searchfile
lines, but it still does not work. Does anyone have a clue?
Upvotes: 4
Views: 865
Reputation: 14757
in
and with
keywordsYou don't need two nested for loops!
Instead use the more pythonic in
keyword like so:
with open("./search_file.txt", mode="r") as search_file:
lines_to_search = search_file.readlines()
with open("./file_to_search.txt", mode="r") as file_to_search:
for line_number, line in enumerate(file_to_search, start=1):
if line in lines_to_search:
print(f"Match at line {line_number}: {line}")
Pro tip: Open your files using the with
statement to automatically close them.
Upvotes: 5
Reputation: 13393
You need to set searchfile
current position to the beginning for every infile
iteration. you can use seek
function for this.
searchfile = open('.\sometext.txt', 'r')
infile = open('.\somefile', 'r')
for line1 in infile:
searchfile.seek(0,0)
for line2 in searchfile:
print line2
searchfile.close()
infile.close()
Upvotes: 5
Reputation: 953
We need a bit more details about what are your objects in this code. But you probably would like to do:
infile = open('.\somefile', 'r')
for line1 in infile:
for line2 in line1:
print line2
searchfile.close()
infile.close()
If your infile is a list of lists - That are the cases where a nested for loop would make sense.
Upvotes: -1
Reputation: 91049
I suppose searchfile
is a file you opened earlier, e. g. searchfile = open('.\someotherfile', 'r')
.
In this case, your construction doesn't work, because a file is an iterable which can be iterated over only once and then it is exhausted.
You have two options here:
What happens in your code?
At the start of the nested for
loops, both your files are open and can be read from.
Whenever the first inner loop run is over, searchfile
is at its end. When the outer loop now comes to process its second entry, the inner loop is like an empty loop, as it just cannot produce more entries.
Upvotes: 6