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

6

我正在尝试找到一种方法,如果第一行的条件为真,则跳过文件中的下两行。 有什么好的方法可以做到这一点吗? 这是我目前的代码...

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
2个回答

5
在Python 2.6或更高版本中,使用:
next(file)
next(file)

要跳过迭代器file的两个项目,即下两行。


1
file.next()
file.next()

我会这样做...


如果我想在阅读特定文件时仅查看从第7行到(文件总行数-4)行之间的数据。 - Indrajeet Gour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接