如何跳过文本文件中的某一行并继续阅读python中的下一行?

Fan*_*ang 2 python

我一直在寻找这个答案,但并没有得到它.

我有一个看起来像这样的文本文件

who are you????
who are you man?
who are you!!!!
who are you? man or woman?
Run Code Online (Sandbox Code Playgroud)

我想跳过它的行man并打印

who are you????
who are you!!!!
Run Code Online (Sandbox Code Playgroud)

我的代码到目前为止

f = open("test.txt", "r")
word = "man"
for line in f:
    if word in line:
        f.next()
    else:
        print line
Run Code Online (Sandbox Code Playgroud)

这仅打印第一行

who are you????
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

谢谢您的帮助.

Gio*_*ano 5

没有必要if elsefor循环中添加语句,因此您可以通过以下方式修改代码:

f = open("test.txt", "r")
word = "man"
for line in f:
    if not word in line:
        print line
Run Code Online (Sandbox Code Playgroud)

此外,您的代码中的问题是您f.next()直接在用于扫描文件的 for 循环中使用。这是因为当该行包含“man”字时,您的代码会跳过两行。

如果if else因为这只是更复杂问题的一个示例而需要保留语句,则可以使用以下代码:

f = open("test.txt", "r")
word = "man"
for line in f:
    if word in line:
        continue
    else:
        print line
Run Code Online (Sandbox Code Playgroud)

使用continue,您可以跳过一个循环的迭代,从而达到您的目标。

正如 Alex Fung 所建议的那样,使用会更好with,因此您的代码会变成这样:

with open("test.txt", "r") as test_file:
    for line in test_file:
        if "man" not in line:
            print line
Run Code Online (Sandbox Code Playgroud)

  • 解释*为什么*`next()`是这个问题会很有用。 (2认同)

Eri*_*nil 5

问题

使用当前代码,当前行包含"man":

  • 你什么都不打印.那是对的.
  • 你也跳过下一行.那是你的问题!
  • f.next()已经for line in f:在每次迭代时被隐含地称为.所以f.next()当你找到"男人"时你实际上会打两次电话.
  • 如果文件的最后一行包含a "man",Python将抛出异常,因为没有下一行.

您可能一直在寻找continue,这也可以达到预期的效果,但是复杂且不必要.请注意,它next在Perl和Ruby中调用,这可能会令人困惑.

who are you????            # <- This line gets printed, because there's no "man" in it
who are you man?           # word in line is True. Don't print anything. And skip next line
who are you!!!!            # Line is skipped because of f.next()
who are you? man or woman? # word in line is True. Don't print anything. 
                           #   Try to skip next line, but there's no next line anymore.
                           #   The script raises an exception : StopIteration
Run Code Online (Sandbox Code Playgroud)

正确的代码

别忘了关闭文件.您可以自动执行以下操作with:

word = "man"
with open("test.txt") as f:
    for line in f:
        if not word in line:
            print line, # <- Note the comma to avoid double newlines
Run Code Online (Sandbox Code Playgroud)