When we read files in Python, we want to detect empty lines and the file send. When we call readline()
we get the next line, if one exists.
With this method, we receive an unambiguous result. An empty string
always means the end of the file has been reached. A newline string
means a blank line was encountered.
Here we use a while-True
loop. We must terminate the loop based on the result of the read line()
method. We have 2 if
-statements.
string
, we break
out of our while-True
loop. We are done reading the file.string
, an empty line was read—but the file has not ended yet. We continue.# Open the file. f = open(r"C:\programs\info.txt", "r") while(True): # Read a line. line = f.readline() # When readline returns an empty string, the file is fully read. if line == "": print("::DONE::") break # When a newline is returned, the line is empty. if line == "\n": print("::EMPTY LINE::") continue # Print other lines. stripped = line.strip() print("::LINE::") print(stripped)Secret insider trading details ABC Lottery ticket numbers 1234 Voting manipulation tips *123::LINE:: Secret insider trading details ::LINE:: ABC ::EMPTY LINE:: ::LINE:: Lottery ticket numbers ::LINE:: 1234 ::EMPTY LINE:: ::LINE:: Voting manipulation tips ::LINE:: *123 ::DONE::
With the strip()
method we remove the leading and trailing whitespace (like a trailing newline) from the string
. This makes the file display better with print.
With readline
we read a line from a file. We can use special logic to detect the EOF (end-of-file) condition. We can handle empty lines and get next lines.