【问题标题】:how to skip certain line in text file and keep reading the next line in python?如何跳过文本文件中的某些行并继续阅读python中的下一行?
【发布时间】:2017-08-19 19:19:16
【问题描述】:

我一直在寻找这个答案,但不太明白。

我有一个像这样的文本文件

who are you????
who are you man?
who are you!!!!
who are you? man or woman?

我想跳过带有man 的行并打印

who are you????
who are you!!!!

到目前为止我的代码

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

这只会打印第一行

who are you????

我应该如何解决这个问题?

感谢您的帮助。

【问题讨论】:

  • 为什么要打电话给f.next()。只需if word not in line: print line。如果wordline 中,则您无需执行任何操作。
  • 打印第一行并不是唯一的问题。您的代码也会引发异常。

标签: python


【解决方案1】:

for循环中不需要添加if else语句,可以这样修改代码:

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

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

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

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

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

正如 Alex Fung 所建议的,最好使用with,所以你的代码会变成这样:

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

【讨论】:

  • 解释为什么 next() 是问题将是有用的。
  • 我建议使用with 确保文件对象最后关闭,
  • 有趣的是,我们的答案在多次编辑后几乎是一致的。你得到我的投票!
  • 感谢您的帮助。你是对的,这只是更复杂问题的一个例子。确实continue 是我一直在寻找的。​​span>
  • @Fang:别忘了用print line,否则你会换行太多
【解决方案2】:

怎么样

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

【讨论】:

    【解决方案3】:

    问题

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

    • 您不打印任何内容。没错。
    • 您也跳过了下一行。那是你的问题!
    • f.next() 已经在每次迭代中被 for line in f: 隐式调用。因此,当找到“man”时,您实际上调用了两次 f.next()
    • 如果文件的最后一行包含"man",Python 将抛出异常,因为没有下一行。

    您可能一直在寻找continue,它也可以达到预期的效果,但会很复杂且不需要。请注意,它在 Perl 和 Ruby 中称为 next,这可能会造成混淆。

    示例

    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
    

    正确的代码

    不要忘记关闭文件。您可以使用 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
    

    【讨论】:

    • 感谢您的解释。我一直在寻找continue,你的答案和下一个答案帮助我理解它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    相关资源
    最近更新 更多