Python中infile对象两次循环仅执行一次的问题排查
为什么Python中第二次遍历文件对象的循环不执行?
你遇到的这个问题完全和文件读取的「指针机制」有关!先看看你写的代码(我帮你整理了正确的缩进格式):
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,但第二段直接跳过;哪怕调换两段顺序,也只有先跑的那段能执行——这是因为文件对象就像一个带「读取指针」的游标:
- 第一次循环时,指针从文件最开头出发,每读一行就往后挪一步,直到把所有内容读完,指针停在了文件的末尾位置。
- 第二次循环的时候,指针已经在末尾了,没有更多内容可以读取,所以循环直接不执行。
给你几个简单易懂的解决办法:
1. 每次循环前重新打开文件
最简单的方式,每次需要遍历的时候重新打开文件,这样指针会自动回到开头:
# 第一段循环 with open("australianFatalities.csv", "r") as infile: for line in infile: words = line.split(",") crash_id = words[0] crash_state = words[1] if crash_state == "NSW": print(crash_id) # 第二段循环,重新打开文件 with open("australianFatalities.csv", "r") as infile: for line in infile: words = line.split(",") crash_id = words[0] crash_state = words[1] if crash_state == "NSW": print(crash_state)
(用with语句会自动帮你关闭文件,比手动调用close()更安全哦)
2. 先把文件内容全部读到列表里
把所有行先存到一个列表中,之后可以反复遍历这个列表:
# 一次性把文件所有行读到列表里 with open("australianFatalities.csv", "r") as infile: all_lines = list(infile) # 第一段循环,遍历列表 for line in all_lines: words = line.split(",") crash_id = words[0] crash_state = words[1] if crash_state == "NSW": print(crash_id) # 第二段循环,再次遍历同一个列表 for line in all_lines: words = line.split(",") crash_id = words[0] crash_state = words[1] if crash_state == "NSW": print(crash_state)
3. 用seek()把指针移回开头
如果不想重新打开或者存列表,可以用infile.seek(0)把指针强制移回文件开头,不过新手可以先试试前两种更直观的方法:
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) # 把指针移回文件开头 infile.seek(0) # 第二段循环 for line in infile: words = line.split(",") crash_id = words[0] crash_state = words[1] if crash_state == "NSW": print(crash_state) infile.close()
这样处理后,两段循环就能正常执行啦!
内容的提问来源于stack exchange,提问作者PlanetAlexanderProjects
相关产品推荐
相关产品推荐

