Distinguishing between blank lines and end of file in Python

5.8k views Asked by At

A situation that I continually run into is the following:

readFile = open("myFile.txt", "r")
while True:
    readLine = readFile.readline()
    if readLine == "":
        #Assume end of file
        break
    #Otherwise, do something with the line
    #...

The problem is that the file I am reading contains blank lines. According to the documentation I have read, file.readline() will return "\n" for a blank line found in a file, but that does not happen for me. If I don't put that blank line condition in the while loop, it continues infinitely, because a readline() executed at or beyond the end of the file returns a blank string.

Can somebody help me create a condition that allows the program to read blank lines, but to stop when it reaches the end of the file?

1

There are 1 answers

5
RemcoGerlich On

Just use a for loop:

for readLine in open("myFile.txt"):
    print(readLine); # Displayes your line contents - should also display "\n"
    # Do something more

Stops automatically at end of file.

If you sometimes need an extra line, something like this might work:

with open("myFile.txt") as f:
    for line in f:
        if needs_extra_line(line):  # Implement this yourself :-)
            line += next(f)  # Add next line to this one
        print(line)

Or a generator that yields the chunks you want to use:

def chunks(file_object):
    for line in file_object:
        if needs_extra_line(line):
            line += next(file_object)
        yield line

Then the function that processes the lines can run a for loop over that generator.