[英]Is there a way to iterate a for loop until a condition is met? (python)
[英]python iterate though text file until condition is met
我想继续遍历文本文件,直到满足循环内的当前条件。
这是示例文本:
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
这是我正在尝试的while循环:
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
如果使用while循环不正确,除了使用while循环之外,还有另一种方法可以做到这一点吗?
谢谢
您要:仅在找到所需行时递增计数器,并在遇到第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
您想将while x < 13
的while x < 13
更改为if语句,以有条件地停止for循环。 例如,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.