all Python 3Files & I/Ofunction
readline()
reading
Read a single line including its trailing '\n'; at end of file it returns an empty string, which is how EOF is detected.
Syntax
f.readline(size=-1)
A blank line in the middle of a file comes back as '\n', which is truthy; only real end of file yields '', so a while line := f.readline() loop will not stop early on an empty line. If the file does not end with a newline, the last line arrives without '\n', which is why rstrip('\n') is safer than slicing off [:-1]. To walk the whole file, for line in f does the same job lazily and without a manual exit condition.
Examples
with open('demo.txt', 'w') as f:
f.write('line1\nline2\n')
with open('demo.txt') as f:
first = f.readline()
second = f.readline()
print(repr(first)) # → 'line1\n'
print(repr(second)) # → 'line2\n'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy