You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python for循环在IDLE/PyCharm中被跳过的原因排查求助

问题分析与解决办法

嘿,我一下子就发现问题出在哪了!

你看这段代码里的x = fh.read()——当你调用这个方法时,它会把整个文件的内容一次性读取到变量x中,同时文件的读取指针会直接跳到文件的末尾。这时候你再用for line in fh去循环读取每一行,指针已经在末尾了,没有任何剩余内容可以读,循环自然就被直接跳过啦。而且看你的代码,x这个变量其实根本没被用到,完全是多余的操作,这就是导致循环失效的核心原因。

解决方法有两种:

方法一:直接删除多余的读取操作

既然x变量没用到,直接删掉x = fh.read()这一行就行,这样文件指针会停留在文件开头,循环就能正常逐行读取内容了:

fname = input("Enter file name: ") 
fh = open(fname + ".txt") 
count = 0 
for line in fh: 
    line = line.rstrip() 
    word = line.split() 
    if len(word) == 0: 
        continue 
    if word[0] != "From": 
        continue 
    else: 
        print(word[1]) 
        count += 1 
print("There were", count, "lines in the file with From as the first word")

方法二:重置文件指针(如果确实需要保留fh.read()

要是你因为某些原因必须先读取整个文件内容,那可以在读取后用fh.seek(0)把文件指针移回开头,这样后续的循环就能正常读取了:

fname = input("Enter file name: ") 
fh = open(fname + ".txt") 
x = fh.read() 
fh.seek(0)  # 将指针重置到文件起始位置
count = 0 
for line in fh: 
    line = line.rstrip() 
    word = line.split() 
    if len(word) == 0: 
        continue 
    if word[0] != "From": 
        continue 
    else: 
        print(word[1]) 
        count += 1 
print("There were", count, "lines in the file with From as the first word")

额外小建议:用with语句更规范

另外,推荐你使用with语句来打开文件,它会在代码块结束后自动关闭文件,避免资源泄漏,代码也更简洁:

fname = input("Enter file name: ") 
count = 0 
with open(fname + ".txt") as fh:
    for line in fh: 
        line = line.rstrip() 
        word = line.split() 
        # 把两个判断合并,代码更简洁
        if len(word) == 0 or word[0] != "From": 
            continue 
        print(word[1]) 
        count += 1 
print("There were", count, "lines in the file with From as the first word")

这样修改后,不管在IDLE、PyCharm还是在线平台,代码都能正常运行,输出那27个邮箱地址并统计总数啦!

内容的提问来源于stack exchange,提问作者Paul Zaino

火山引擎 最新活动