python iterate though text file until condition is met

眉间皱痕 提交于 2019-12-02 09:34:01

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!