I have the following text file (file.txt):
1
2 inside
3
4 outside
5
6
and when I run the following code:
with open("file.txt") as f:
for value in f:
print("outer loop (value): ",value,end="")
if "inside" in value:
lstItem = []
lstItem.append(value)
for i,value in enumerate(f):
print("inner loop (index:value): ",i,value,end="")
lstItem.append(value)
if "outside" in value:
break
print(),print(lstItem),print()
this is my output:
outer loop (value): 1
outer loop (value): 2 inside
inner loop (index:value): 0 3
inner loop (index:value): 1 4 outside
['2 inside\n', '3\n', '4 outside\n']
outer loop (value): 5
outer loop (value): 6
So I get why "2 inside" is not being included in the nested loop output (it resides outside of it), but what I don't get is why the file pointer is advanced to the next line upon calling the inner loop.
I have "2 inside" as part of the list (which is what I want), but I also would like to see "2 inside" be part of the inner loop output with its index next to it, but I can't figure out how to that. I even tried commenting out the lstItem.append(value) statement to see if it would keep the file pointer from advancing, but that just excludes that value from the list, which is not what I want.