python - Python:“infile”for循环不会第二次运行
问题描述
我有两个从文件中读取的 for 循环。它们都完全相同,除了if
它们内部的语句。
infile = open("australianFatalities.csv", "r")
for line in infile:
words = line.split(",")
crash_id = words[0]
crash_state = words[1]
if crash_state == "NSW":
print(crash_id)
for line in infile:
words = line.split(",")
crash_id = words[0]
crash_state = words[1]
if crash_state == "NSW":
print(crash_state)
问题是第一个循环运行,但第二个没有。我知道这一点,因为crash_id
将被打印,但crash_state
不会。如果我切换crash_id
和crash_state
左右,状态会打印,但 ID 不会。此代码已与我的主项目隔离,但显示相同的问题。
为什么循环不会第二次运行?它与读取文件有关吗?
我是 Python 新手,所以答案需要保持一些基本的。
解决方案
当你在 python 中迭代一个文件对象时,每次迭代后当前位置都会改变。
因此,当您尝试再次遍历文件对象时,光标位于文件末尾。
您可以通过再次打开文件来解决此问题,或者更好:通过fd.seek(0)
在第二个循环之前调用。
推荐阅读
- google-apps-script - 云构建 API 部署:在 Google Apps 上运行脚本不起作用
- scheme - 使用do循环近似欧拉数(方案)
- javascript - .js 和 .mjs 文件有什么区别?
- php - 无法打开流:/var/www/html/fisecal-backend/vendor/composer/ClassLoader.php:444 中没有这样的文件或目录)
- performance - 没有 HasCallStack 时,errorWithoutStackTrace 会比 error 快吗?
- rust - 如何创建允许将索引映射到切片中的可变项的迭代器
- c# - 元素
- php - 将上传的图像保存到我的文件的问题
- python - 在openpyxl中更改整列的number_format
- azure-devops - 如何在 azure devops 中显示每个阶段的列