python - 使用 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()
。
为什么会这样?
解决方案
f.read()
从文件中的当前位置开始。因此,当您为同一个文件对象调用两次时,第二次就没有什么可读取的了。
推荐阅读
- css - 使用 CSS 隐藏类而不级联
- opengl - 如何在 1D 缓冲区中生成 2D 纹理并将其加载到 OpenGL 中?
- c++ - 我们可以在可变参数模板参数之前有可变参数概念吗?
- rust - 如何使用 `serde_json_core` 反序列化没有分配的数组?
- mongodb - 使用排序方法时 mongodb 中的分页问题。分页在按新排序时工作正常,但在按旧排序时出现问题
- java - Jackson 在反序列化的错误级别上搜索方法
- java - JasperReport 3.1 是否与 JAVA 8 一起运行?
- forms - 将 xcframework 导入 Xamarin 表单
- html - Bootstrap 5下拉菜单适用于父页面但不适用于子页面
- raster - 使用 pyqgis 列出 Geopackage 中的所有栅格图层