HomeSearch

Python readline Example: Read Next Line

Use the readline method to read files. Handle empty lines, ends of files and gets next lines.

Readline. When we read files in Python, we want to detect empty lines and the file's end. 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.WhileIf

Break: When the line equals an empty string, we break out of our while-True loop. We are done reading the file.

Continue: When we encounter a newline string, an empty line was read—but the file has not ended yet. We continue.

Python program that uses readline # 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) Contents: info.txt Secret insider trading details ABC Lottery ticket numbers 1234 Voting manipulation tips *123 Output ::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.StripConsole, print

Documentation. The Python documentation is excellent. It indicates the result of readline is unambiguous. But we must know what values to test for.

Quote: If f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

Input and Output: Python.org

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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.