如何在不检查空行的情况下循环直到 Python 中的文件末尾?

How to while loop until the end of a file in Python without checking for empty line?

我正在写一个作业来计算文件中元音的数量,目前在我的class中我们只使用这样的代码来检查文件的结尾:

vowel=0
f=open("filename.txt","r",encoding="utf-8" )
line=f.readline().strip()
while line!="":
    for j in range (len(line)):
        if line[j].isvowel():
            vowel+=1

    line=f.readline().strip()

但是这次我们的作业我们教授给的输入文件是一篇完整的文章,所以整个文本中有几个空行来分隔段落等等,这意味着我当前的代码只能计算到第一个空行.

除了检查该行是否为空之外,还有什么方法可以检查我的文件是否已到达末尾?最好以与我目前的代码类似的方式,它在 while 循环的每一次迭代中检查一些东西

提前致谢

不要以这种方式遍历文件。而是使用 for 循环。

for line in f:
    vowel += sum(ch.isvowel() for ch in line)

事实上你的整个程序只是:

VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
    vowel = sum(ch in VOWELS for line in f for ch in line.strip())

就是说,如果您出于某些误入歧途的原因真的想继续使用 while 循环:

while True:
    line = f.readline().strip()
    if line == '':
        # either end of file or just a blank line.....
        # we'll assume EOF, because we don't have a choice with the while loop!
        break

我在遵循上述建议时发现 对于 f 中的行: 不适用于 pandas 数据框(不是有人说会) 因为数据框中文件的末尾是最后一列,而不是最后一行。 例如,如果您有一个包含 3 个字段(列)和 9 个记录(行)的数据框,for 循环将在第 3 次迭代后停止,而不是在第 9 次迭代后停止。 特蕾莎

找到文件的结束位置:

f = open("file.txt","r")
f.seek(0,2) #Jumps to the end
f.tell()    #Give you the end location (characters from start)
f.seek(0)   #Jump to the beginning of the file again

然后你可以:

if line == '' and f.tell() == endLocation:
   break
import io

f = io.open('testfile.txt', 'r')
line = f.readline()
while line != '':
        print line
        line = f.readline()
f.close()