![](/img/trans.png)
[英]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.