Python For 循环似乎被跳过了

Python For loop seems to be getting skipped over

这是我的第一个问题,请多多包涵。 我正在通过在线课程学习 Python。我使用 Trinket 完成了这项任务,它在那里工作。我通过在线评分系统提交了代码,它也通过了。所以,我已经得到了 'credit' 这个作业。

当我在空闲或 PyCharm 下尝试时,代码不起作用。它似乎完全跳过了for循环。

我已经看过关于此类问题的其他答案,但我不知道如何将它们应用到我的情况中。请帮助我理解为什么我的 for 循环似乎被跳过了。

fname = input("Enter file name: ")
fh = open(fname + ".txt")
x = fh.read()
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")

在使用的.txt文件中,一一打印出27个邮箱地址,最后一行给出总数。正如我所说,它适用于 Trinket 和在线代码评分器,但不适用于 PyCharm 或 Idle。

提前致谢。

您可以尝试更换

for line in fh:

for line in x:

或删除 x = fh.read(),因为它会读取整个文件并为循环留下一个空文件

当您执行 x = fh.read() 时,您正在读取文件的内容并将其存储在变量 x 中。

来自Python documentation

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

所以,一旦文件被完全读取,fh 已经在文件末尾并且用 for 循环迭代它不会产生任何新行。您在这里有两个选择:

  1. for line in fh: 更改为 for line in x:
  2. 删除x = fh.read()