我想继续遍历文本文件,直到满足循环中的当前条件。
这是示例文本:
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循环不正确,还有另一种方法可以实现吗?
谢谢
答案 0 :(得分:4)
您希望:只有当您找到要查找的行时才会递增计数器,并在每次点击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
答案 1 :(得分:1)
您希望将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