Readline. 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.
Example program. 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.
Info When the line equals an empty string, we break out of our while-True loop. We are done reading the file.
And When we encounter a newline 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::
Strip. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 15, 2025 (edit link).