5

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?

jdrobers
  • 139
  • 1
  • 3
  • 9

1 Answers1

3

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.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • The only problem I have with that is that for some parts of the file, I have to read two lines in order to gather all of the data I need. In other words, I would execute a second readline() within the same loop. I'm not sure if I can do that using the for loop you describe. – jdrobers Nov 19 '14 at 20:34
  • You can do that if you assign the open file to a variable, and then call `next()` to get the next value out of the iterator. I'll edit. – RemcoGerlich Nov 19 '14 at 20:35
  • @jdrobers Then call `next()` on the file object during the loop, if a `StopIteration` error is raised the file has reached its end. – Ashwini Chaudhary Nov 19 '14 at 20:36
  • 1
    Well, I tried converting to a "for" loop and I get the same issue. Blank lines terminate the loop (I have removed the condition to break if readLine == "", btw.) If it means anything, I'm using Python 2.7.5. Are there any other workarounds? – jdrobers Nov 19 '14 at 20:51
  • No, I'm quite sure that if you get a blank line, you have in fact reached the end of the file. Otherwise that's not a line, and it would have continued. Maybe a problem with your file? – RemcoGerlich Nov 19 '14 at 21:18