The readlines()
function in Python takes a text file as input and stores each line in the file as a separate element in a list.
Imagine a book with thousands of sentences where each sentence is numbered such that given the index, you could extract that particular sentence from the book itself. Then a book would be called a list of sentences, or in our language, a list of strings.
readlines()
in PythonThe first step in learning about this function is to learn about its syntax. The snippet below shows the signature of the function.
To understand the signature let’s break it down into parameter and return value.
This function takes in only one parameter (optional).
sizehint
: This is the number of bytes, rounded up to the nearest internal buffer size, that should be read from the file.Note: The function, without
sizehint
given, reads a file till it reaches theEOF
and then returns an empty string.
The function returns a list of all the lines which can then be used for further manipulations or simply printed.
The illustration below shows how this is done.
Now that we know how to call the function and how it works, let’s look at examples for a better understanding.
readlines()
without any parameterThe example below shows how to use readlines()
to store the result in a list and then display it. The function reads till the EOF
.
file_input = open("read.txt",'r')list = file_input.readlines()print(list)
readlines()
with a parameterThe example below reads the same file but this time with the parameter set to 8 bytes. Hence, only the elements until 8 bytes are read from the file.
file_input = open("read.txt",'r')list = file_input.readlines(8)print(list)