readline Example: Read Next LineUse the readline method to read files. Handle empty lines, ends of files and gets next lines.
This page was last reviewed on May 21, 2023.
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.
An 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.
A summary. 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 21, 2023 (edit).
© 2007-2024 Sam Allen.