首页 > 解决方案 > 使用 open() 的输出与保存到变量时的不同行为

问题描述

我在 python 中有一个字符串列表,我想找出哪些不包含任何错误的子字符串,这些子字符串是我从文件中读取的。这是我在 python 2 中的代码:

with open("badchars.txt", "w") as f:
  f.write("a b c")

mywords = ["good", "bad"]

print [
       word for word in mywords
          if all(
                 badchar not in word
                    for badchar in open("badchars.txt").read().split()
                )
      ]

with open("badchars.txt") as f:
  print [
         word for word in mywords
            if all(
                   badchar not in word
                      for badchar in f.read().split()
                  )
        ]

我希望两行都打印 ["good"],但是第一行的行为符合预期,第二行给出 ["good", "bad"]。我不明白为什么。

print如果我更改为.python 3,也会发生同样的事情print()

为什么会这样?

标签: pythonlist-comprehension

解决方案


f.read()从文件中的当前位置开始。因此,当您为同一个文件对象调用两次时,第二次就没有什么可读取的了。


推荐阅读