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?
Just use a for loop:
Stops automatically at end of file.
If you sometimes need an extra line, something like this might work:
Or a generator that yields the chunks you want to use:
Then the function that processes the lines can run a for loop over that generator.