使用 for 循环读取文件时跳过行

2024-06-19

我试图找出一种方法,如果第一行中的条件为真,则跳过文件中的接下来两行。有什么好的方法可以做到这一点吗?这是我到目前为止所拥有的......

def main():
    file = open(r'C:\Users\test\Desktop\test2.txt', 'r+')
    ctr = 1
    for current_line in file:
        assert ctr<3
        if current_line[0:6] == str("001IU"):
            pass
        else:
            if ctr == 1 and current_line[9:11] == str("00"):
                do something...
                ctr += 1
            elif ctr == 1 and current_line[9:11] != str("00"):
                pass #I want it to skip the next two lines in the loop
            elif ctr == 2:
                do something...
                ctr = 1
            else:
                raise ValueError

在 Python 2.6 或更高版本中,使用

next(file)
next(file)

跳过迭代器的两项file,即接下来的两行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 for 循环读取文件时跳过行 的相关文章

随机推荐