【问题标题】:skipping a line while reading a file with a for loop使用 for 循环读取文件时跳过一行
【发布时间】:2011-12-21 15:26:42
【问题描述】:

如果第一行中的条件为真,我正在尝试找出一种跳过文件中接下来两行的方法。关于这样做的好方法有什么想法吗?这是我到目前为止所拥有的......

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 file-io for-loop iterator


    【解决方案1】:

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

    next(file)
    next(file)
    

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

    【讨论】:

      【解决方案2】:
      file.next()
      file.next()
      

      我会这样做......

      【讨论】:

      • 如果我只想查看从第 7 行到之前(文件的总行数 - 4)行之间的数据,而我正在读取该特定文件
      猜你喜欢
      • 2017-05-09
      • 2015-05-08
      • 1970-01-01
      • 2019-04-14
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      相关资源
      最近更新 更多