Trusted answers to developer questions

Learning about the readlines() function in Python

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.


How to implement readlines() in Python

The first step in learning about this function is to learn about its syntax. The snippet below shows the signature of the function.

Syntax

To understand the signature let’s break it down into parameter and return value.

Parameter

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 the EOF and then returns an empty string.

Return Value

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.

The text file to be read
1 of 7

Examples

Now that we know how to call the function and how it works, let’s look at examples for a better understanding.

1. Using readlines() without any parameter

The example below shows how to use readlines() to store the result in a list and then display it. The function reads till the EOF.

main.py
read.txt
file_input = open("read.txt",'r')
list = file_input.readlines()
print(list)

2. Using readlines() with a parameter

The 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.

main.py
read.txt
file_input = open("read.txt",'r')
list = file_input.readlines(8)
print(list)

RELATED TAGS

input
lines
list
python
reading lines
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?