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 循环之外,还有其他方法可以实现吗?
谢谢
您想将 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
您想要:仅在找到要查找的行时增加计数器,并在达到 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
我想继续遍历文本文件,直到满足循环内的当前条件。
这里是示例文本:
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 循环之外,还有其他方法可以实现吗?
谢谢
您想将 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
您想要:仅在找到要查找的行时增加计数器,并在达到 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