I have a loop that is parsing lines of a text file:
for line in file:
if line.startswith('TK'):
for item in line.split():
if item.startwith('ID='):
*stuff*
if last_iteration_of_loop
*stuff*
I need to do a few assignments, but I can't do them until the last iteration of the second for loop. Is there a way to detect this or to know if I'm at the last item of line.split()? As a note, the items in the second for loop are strings, and their content are unknown at runtime, so I can't look for a specific string as flag to let me know I'm at the end of the list.
Just refer to the last line outside the for loop:
for line in file:
if line.startswith('TK'):
item = None
for item in line.split():
if item.startwith('ID='):
# *stuff*
if item is not None:
# *stuff*
The item variable is still available outside the for loop:
>>> for i in range(5):
... print i
...
0
1
2
3
4
>>> print 'last:', i
last: 4
Note that if your file is empty (no iterations through the loop) item will not be set; this is why we set item = None before the loop and test for if item is not None afterwards.
If you must have the last item that matched your test, store that in a new variable:
for line in file:
if line.startswith('TK'):
lastitem = None
for item in line.split():
if item.startwith('ID='):
lastitem = item
# *stuff*
if lastitem is not None:
# *stuff*
Demonstration of the second option:
>>> lasti = None
>>> for i in range(5):
... if i % 2 == 0:
... lasti = i
...
>>> lasti
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With