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

时间:2017-03-27 07:32:36

标签: python

我一直在寻找这个答案但是没有得到它。

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

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????

我该如何解决这个问题?

感谢您的帮助。

3 个答案:

答案 0 :(得分:5)

问题

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

  • 你不打印任何东西。那是对的。
  • 你也跳过下一行。那是你的问题!
  • {li> 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

答案 1 :(得分:4)

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

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

此外,代码中的问题是您在用于扫描文件的for循环中直接使用f.next()。这是因为当该行包含&#34; man&#34;单词,你的代码会跳过两行。

如果您想保留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

答案 2 :(得分:1)

怎么样

unsigned int