使用with..open时跳过一行

时间:2015-06-08 07:21:37

标签: python python-2.7

我正逐行阅读一个大文本文件

\textcolor{\red}{...} doesn't work in .bib file

如果找到匹配项,我想跳过一行 - 如何使用import re with open("file.txt") as f: for line in f: if re.search(regex stuff, line): #skip next line 语句执行此操作?

3 个答案:

答案 0 :(得分:2)

您的条件应为if not search(regex stuff,line)

import re

with open("file.txt") as f:
    for line in f:
        if not re.search(regex stuff, line):
            continue # or do something

答案 1 :(得分:1)

你需要一些状态。我将该州称为skipnext

import re

skipnext = False

with open("file.txt") as f:
 if skipnext:
  skipnext = False
  continue
 for line in f:
  if re.search(regex stuff, line):
   skipnext = True

答案 2 :(得分:1)

在原始文件类似obj next上使用f

import re

with open("file.txt") as f:
    for line in f:
        if re.search(regex, line):
            next_line = next(f, '')

这会将以下行的内容放在next_line中,或者如果您在文件的最后一行匹配,则它将是一个空字符串。如果需要,可以使用next_line执行某些操作。当for - 循环恢复时,它将来自该行之后的行...