all Python 3Files & I/Ofunction
io.IOBase.readlines()
reading
Read the whole file into a list of lines, keeping the trailing '\n'; strip them with .rstrip() or use .splitlines() on the result of .read().
Syntax
f.readlines(hint=-1)
For a plain pass over the lines you do not need readlines(): for line in f does the same thing lazily, without pulling the whole file into memory or building a list. The hint argument is not a hard cut — whole lines are read until their combined size exceeds hint, so you can get back somewhat more than you asked for.
Examples
with open('demo.txt', 'w') as f:
f.write('line1\nline2\nline3\n')
with open('demo.txt') as f:
lines = f.readlines()
print(lines) # → ['line1\n', 'line2\n', 'line3\n']
with open('demo.txt') as f:
print([s.rstrip() for s in f.readlines()]) # → ['line1', 'line2', 'line3']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy