Python readlines function
last modified November 29, 2026 Python 3.15
In this article we show how to use the readlines method to read all
lines of a file into a list. We look at the newline characters that the list
keeps, the optional size hint, binary files, and the differences between
readlines, list, and plain iteration.
Opening files is explained in Python open function, reading a whole file in Python read file, and reading a single line in Python readline function.
The text file
The examples work with a small file of city names, saved in UTF-8 with one name per line. The file has six lines and ends with a newline character.
Paris Prague Vienna Kraków Budapest Warsaw
The accented ó in Kraków takes two bytes in UTF-8 but
counts as a single character, which matters when the size hint is used.
Reading all lines
The readlines method reads from the current position to the end of
the file and returns a list of strings in text mode. Every string keeps the
line terminator, which makes the list a faithful copy of the file.
with open('cities.txt', encoding='utf-8') as f:
lines = f.readlines()
print(len(lines))
print(lines[:2])
print(repr(lines[-1]))
The list has six items. Printing the first two shows the \n at the
end of each string, and repr on the last one shows it too. That
newline is the only difference between a line and the text you would print with
print.
$ python read_all.py 6 ['Paris\n', 'Prague\n'] 'Warsaw\n'
Line endings
The trailing newline is usually not wanted. The right tool depends on what
should be removed: rstrip('\n') drops only the terminator, while
strip() also removes leading and trailing spaces, which may be part
of the data.
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write(' milk \n')
f.write('bread\n')
f.write('eggs')
with open('notes.txt', encoding='utf-8') as f:
lines = f.readlines()
print([line.rstrip('\n') for line in lines])
print([line.strip() for line in lines])
print(repr(lines[-1]))
The first list keeps the spaces around milk and removes only the
newlines. The second list removes the spaces as well. The last line of the file
has no newline, so its string is already just eggs; code that
assumes every line ends with \n fails on such a final line.
In text mode with the default newline=None, Windows and old Mac
line endings are translated to \n while the file is read, so
rstrip('\n') is enough. If the file was opened with
newline='', the list can contain \r\n and both
characters have to be removed.
$ python strip_lines.py [' milk ', 'bread', 'eggs'] ['milk', 'bread', 'eggs'] 'eggs'
The size hint
readlines accepts an optional size hint. Instead of the whole file,
it then returns complete lines whose total length is about the hint. No line is
ever cut in the middle, so the result can be a little longer than requested.
with open('cities.txt', encoding='utf-8') as f:
while chunk := f.readlines(10):
print(len(chunk), chunk[0].rstrip('\n'), chunk[-1].rstrip('\n'))
Each call returns roughly ten characters worth of lines. The loop keeps calling until the method returns an empty list at the end of the file, so the whole file is processed two lines at a time. The hint is a soft limit that saves memory on large files; for simple processing, iterating over the file is easier.
$ python read_chunks.py 2 Paris Prague 2 Vienna Kraków 2 Budapest Warsaw
Position and end of file
readlines starts at the current file position, not at the beginning
of the file. This is useful when a header or a first record has already been
read with another method.
with open('cities.txt', encoding='utf-8') as f:
print(repr(f.readline()))
rest = f.readlines()
print(len(rest), rest[0].rstrip('\n'))
print(f.readlines())
The first readline consumes Paris\n, so
readlines returns the five remaining lines. A second call finds the
pointer at the end of the file and returns an empty list, not an error and not
None.
$ python position.py 'Paris\n' 5 Prague []
Binary files
In binary mode the same method returns a list of bytes objects.
No decoding or newline translation takes place, so the line endings are
whatever the file contains.
with open('raw.bin', 'wb') as f:
f.write(b'alpha\r\nbeta\r\ngamma\r\n')
with open('raw.bin', 'rb') as f:
lines = f.readlines()
print(lines)
print(len(lines[0]))
The list holds three byte strings, and each of them still ends with
\r\n. The first one is seven bytes long: five letters of
alpha plus two line-ending bytes. Text mode would have returned
'alpha\n' instead.
$ python read_binary.py [b'alpha\r\n', b'beta\r\n', b'gamma\r\n'] 7
readlines, list, and iteration
Calling list on a file object gives exactly the same list as
readlines. The difference appears with large files: the list holds
every line in memory, while a for loop over the file object reads
one line at a time.
with open('cities.txt', encoding='utf-8') as f:
lines = f.readlines()
with open('cities.txt', encoding='utf-8') as f:
same = list(f)
print(lines == same)
with open('cities.txt', encoding='utf-8') as f:
for line in f:
if line.startswith('Krak'):
print(line.rstrip('\n'))
break
The two lists compare equal. The loop opens the file again and stops at the
first match, so the remaining lines are never read. Use readlines
when the whole file is needed for random access or several passes, and
iteration when the lines can be processed one by one.
$ python list_compare.py True Kraków
Working with the list
Once the lines are in a list, ordinary list operations apply: comprehensions can
clean or filter them, join can put them back into one string, and
writelines can save the list to another file.
with open('cities.txt', encoding='utf-8') as f:
lines = f.readlines()
names = [line.rstrip('\n') for line in lines]
long_names = [name for name in names if len(name) > 5]
print(long_names)
print(' | '.join(names))
with open('copy.txt', 'w', encoding='utf-8') as f:
f.writelines(lines)
with open('copy.txt', encoding='utf-8') as f:
print(f.readlines() == lines)
The first comprehension removes the newlines, and the second keeps the names
longer than five characters. join builds a single string with a
separator. writelines writes the strings exactly as they are, so
the newlines kept by readlines are what makes the copy line up; it
does not add separators itself.
$ python process_list.py ['Prague', 'Vienna', 'Kraków', 'Budapest', 'Warsaw'] Paris | Prague | Vienna | Kraków | Budapest | Warsaw True
Source
IOBase.readlines – Python documentation
Methods of File Objects – Python Tutorial
In this article we have read files into lists of lines, cleaned the line
endings, limited reading with the size hint, and compared
readlines with iteration. See also
Python read file,
Python readline function,
Python read function,
Python writelines function, and
Python open function.
Author
List all Python tutorials.