Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am searching line from one file into another file and if found, i will print it. I am using Nested for loop, the problem that inner loops runs only on first line of outer loop and stops.

What I have tried:

flooback=open('loopback.txt')
fsid=open('sid.txt')
bucket=None
for line in flooback:
	bucket=line.strip()
	for s in fsid:
		s=s.strip()
		if s==bucket:
			print(s)
Posted
Updated 2-Aug-22 12:21pm

1 solution

Quote:
I am using Nested for loop, the problem that inner loops runs only on first line of outer loop and stops.

you need to understand that fsidis an object of type file, and it contains a pointer telling actual position in file.
When end of file is reached, it knows that there is nothing more to read.
You need to reset the pointer position to beginning of file before reading again with inner loop. The easiest solution is open the file just before starting the inner loop, and close the file just at the end of inner loop.
Python
flooback=open('loopback.txt')
fsid=open('sid.txt') # remove this line from code
bucket=None
for line in flooback:
	bucket=line.strip()
	# open sid.txt here
	for s in fsid:
		s=s.strip()
		if s==bucket:
			print(s)
	# close sid.txt here
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900