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

I am writing an assignment for counting the number of vowels in a file, currently in my class we used only such code to check the end of the file:

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()

But this time, for our assignment, the input file provided by our professor is a whole essay, so there are several empty lines in the text to separate paragraphs and something else, which means that my current code will be counted only up to the first empty line .

Is there any way to check if my file has reached the end besides checking for the presence of a line? Preferably similarly, I have my code now, where it checks something each iteration of the while loop

Thanks in advance

+4
3

. 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
+18

:

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
0

I found that following the suggestions above, for a line in f: does not work for pandas dataframe (not that anyone said it would be) because the end of the file in the data frame is the last column, not the last line. for example, if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the third iteration, and not after the ninth iteration. Teresa

-1
source

All Articles