Reputation: 552
i would like to continue iterating through the text file until the current condition inside the loop is met.
here is the sample text:
10-01 N/A
10-02 N/A
10-03 N/A
10-04 N/A
10-05 N/A
10-06 N/A
10-07 N/A
10-08 N/A
10-09 N/A
10-10 N/A
10-11 N/A
10-12 N/A
===04===...... # Skip line until '01' is found
===12===...... # Skip line until '01' is found
05-01 N/A
05-02 N/A
05-03 N/A
05-04 N/A
05-05 N/A
05-06 N/A
===08===...... # Skip line until '07' is found
===11===...... # Skip line until '07' is found
05-07 N/A
05-08 N/A
05-09 N/A
05-10 N/A
05-11 N/A
05-12 N/A
this is the while loop i am trying:
x = 1
with open(loc_path + 'SAMPLEDATA.TXT', 'rb') as textin:
for line in textin:
while x < 13:
if line[3:].startswith(str(x).zfill(2)):
print '%r' % line
else:
x = 1 # Restart loop
x += 1
is there another way to accomplish this besides using a while loop if using a while loop is not correct?
thank you
Upvotes: 0
Views: 3662
Reputation: 29740
You want to: only increment the counter when you find the line you're looking for, and reset it whenever it hits 13
x = 1
with open(loc_path + 'SAMPLEDATA.TXT', 'rb') as textin:
for line in textin:
if line[3:].startswith(str(x).zfill(2)):
print '%r' % line
x += 1
if x >= 13:
x = 1 # reset counter
Upvotes: 4
Reputation: 19780
You want to change your while x < 13
into an if-statement to conditionally stop the for-loop. E.g.,
x = 1
with open(loc_path + 'SAMPLEDATA.TXT', 'rb') as textin:
for line in textin:
if line[3:].startswith(str(x).zfill(2)):
print '%r' % line
else:
x = 1 # Restart counter
x += 1
if x >= 13:
break # Stop reading
Upvotes: 1