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

start reading file from specific line python
python read file in chunks of lines
python keep reading until end of file
end of file when reading a line in python
python read large file in chunks
while line is not empty python
python readline end of file
how to read multiple lines from a file in python

I'm writing an assignment to count the number of vowels in a file, currently in my class we have only been using code like this to check for the end of a 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 given by our professor is an entire essay, so there are several blank lines throughout the text to separate paragraphs and whatnot, meaning my current code would only count until the first blank line.

Is there any way to check if my file has reached its end other than checking for if the line is blank? Preferably in a similar fashion that I have my code in currently, where it checks for something every single iteration of the while loop

Thanks in advance

Don't loop through a file this way. Instead use a for loop.

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

In fact your whole program is just:

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

That said, if you really want to keep using a while loop for some misguided reason:

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

Python: How to read and write files, How do you read a file until the end in Python? In this tutorial, you'll learn about indefinite iteration using the Python while loop. You’ll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.

Find end position of file:

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

Then you can to:

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

Python "while" Loops (Indefinite Iteration) – Real Python, () and readline() methods returns an empty string, while readlines() returns an empty list ( [] ). The syntax of a while loop in Python programming language is − while expression: statement(s) Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

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

What value does readline return when reaching the end of the file in , How do I know if EOF is reached in Python? I have the code below, I wish to run the while loop to remove a specific value from the list but not remove it on a certain index and still loop through the whole list without removing that specific

Reading Files with Python, What is returned when the readline method reaches the end of the file? The break, continue, and pass statements in Python will allow you to use for loops and while loops more effectively in your code. To work more with break and pass statements, you can follow our project tutorial “How To Create a Twitterbot with Python 3 and the Tweepy Library.”

3.3. While Statements, has been reached, while a blank line is represented by '\n' , a string containing only a single newline. Checking for an end of file with readline() The readline() method doesn't trigger the end-of-file condition. Instead, when data is exhausted, it returns an empty string.

Python readline Example: Read Next Line, But this time for our assignment the input file given by our professor is an entire essay, so there are several blank lines throughout the text to separate paragraphs  In this tutorial, we’ll describe multiple ways in Python to read a file line by line with examples such as using readlines(), context manager, while loops, etc. After this, you can adopt one of these methods in your projects that fits the best as per conditions. Python has made File I/O super easy for the programmers.

Comments
  • This isn't really worth an answer on its own, but if you skip calling strip() on your lines, the rest of your code would work just fine. The call to readline() on a line with no text will return "\n", while at the end of the file it will return "" (an empty string). Another alternative is to call read() to get all of the file's text in a single long string which you can then iterate over. You don't actually need to count the vowels line by line.
  • Nitpicking... you should add as f to the with statement.
  • Python doesn't throw EOFError for file.readline() (though I wish it did and many answers claim it does). Instead, look for an unterminated empty line (e.g., line=f.readline(); if not line: ...) See also docs.python.org/2/library/exceptions.html#exceptions.EOFError
  • It would take me a term of my natural life to get 17.8k reputation in SO but there is a correction if line == '': and not if line = ''. I know that is not remotely connected as part of the discussion but felt like pointing it out. :) :) @AdamSmith
  • @DurwasaChakraborty thanks! Doesn't matter how long you've been coding, you can still typo :)
  • @Maor I know this is very old, but I'm assuming you're looking at something like while not flag: do_stuff() versus for thing in stuff: do_stuff(); if flag: break. I would GENERALLY prefer a for loop there, but it strongly depends on individual circumstance. You're not going to see much of a performance difference, so prefer instead to make your code more readable.
  • Because pandas and dataframes within pandas were not mentioned in this question, I would advise this to be made into a comment on the original post rather than an answer. (But, this is a little late to the post so maybe we just leave it alone.)