首页 > 解决方案 > 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_idcrash_state左右,状态会打印,但 ID 不会。此代码已与我的主项目隔离,但显示相同的问题。

为什么循环不会第二次运行?它与读取文件有关吗?

我是 Python 新手,所以答案需要保持一些基本的。

标签: python

解决方案


当你在 python 中迭代一个文件对象时,每次迭代后当前位置都会改变。

因此,当您尝试再次遍历文件对象时,光标位于文件末尾。

您可以通过再次打开文件来解决此问题,或者更好:通过fd.seek(0)在第二个循环之前调用。


推荐阅读