Each call to readline() reads from the file's current position up to and including the next newline character, or up to the end of the file if there's no more newline, advancing the position so the next call returns the following line. Unlike iterating over the file directly with a for loop, calling readline() explicitly gives you precise, one-line-at-a-time control — useful for skipping a header line, or reading lines conditionally. At the end of the file, readline() returns an empty string, which is distinct from a blank line, which returns just a newline character.
1Understanding readline()
Each call to readline() reads from the file's current position up to and including the next newline character, or up to the end of the file if there's no more newline, advancing the position so the next call returns the following line. Unlike iterating over the file directly with a for loop, calling readline() explicitly gives you precise, one-line-at-a-time control — useful for skipping a header line, or reading lines conditionally. At the end of the file, readline() returns an empty string, which is distinct from a blank line, which returns just a newline character.
Reaching the end of the file returns an empty string from readline(), while a genuinely blank line in the file returns just a newline character — checking that the result is falsy correctly distinguishes end-of-file from a blank line, since an empty string is falsy but a lone newline character is truthy.
with open("log.txt", "w") as f:
f.write("First line\nSecond line\n")
with open("log.txt", "r") as f:
print(repr(f.readline()))
print(repr(f.readline()))
print(repr(f.readline()))2Practical Example
Here is a real-world application of readline() showing how it is used in production Python code.
with open("data.csv", "w") as f:
f.write("name,age\nAlice,30\nBob,25\n")
with open("data.csv", "r") as f:
header = f.readline()
for line in f:
print(line.strip())3Best Practices
Follow these guidelines when working with readline():
1. Prefer iterating over a file object directly (for line in f:) over manually calling readline() in a loop, unless you need precise control over exactly how many lines to read
2. Use readline() to explicitly skip or inspect a header line before processing the rest of a file in a loop
3. Check for a falsy result to detect end-of-file, remembering that a blank line and end-of-file are different
Tip: Reaching the end of the file returns an empty string from readline(), while a genuinely blank line in the file returns just a newline character — checking that the result is falsy correctly distinguishes end-of-file from a blank line, since an empty string is falsy but a lone newline character is truthy.
with open("log.txt", "w") as f:
f.write("First line\nSecond line\n")
with open("log.txt", "r") as f:
print(repr(f.readline()))
print(repr(f.readline()))
print(repr(f.readline()))