AppDividend
Latest Code Tutorials

Python readlines: How to Use readlines() Function

The readline() is a built-in file method that helps read one complete line from the given file. There is also a function called readlines() which we will discuss today in this article.

Python readlines()

The file readlines() is a built-in Python function that returns all lines in the file as a list where each line is an item in the list object. The readlines() function accepts the hint parameter to limit the number of lines returned.

The readlines() function can be used for small files, as it reads the whole file content to the memory, then splits it into separate lines.

The readlines() function reads until the end of the file, using the readline() function internally, and returns a list with all the lines read from the file.

Syntax

file.readlines(hint)

Parameters

The readlines() function takes a hint as an optional parameter which is the number of bytes returned exceed the hint number; no more lines will be returned. The default value is  -1, which means all lines will be returned.

Example

Let’s declare a list.

data = ["You\n", "are\n", "Wizard\n", "Harry\n"]

Now, we will write this list into a text file.

fl = open("app.txt", "w")
fl.writelines(data)
fl.close()

We opened a file in write mode and then used the writelines() function to write the data into the text file.

To read that text file line by line, use the readlines() function and for loop.

count = 0

# It strips the newline character
for line in lines:
    count += 1
    print("Line{}: {}".format(count, line.strip()))

Here, we put the counter to count the number of lines to show in the Python console.

Our complete program looks like this.

data = ["You\n", "are\n", "Wizard\n", "Harry\n"]

# writing to file
fl = open("app.txt", "w")
fl.writelines(data)
fl.close()

# Using readlines()
fl = open("app.txt", "r")
lines = fl.readlines()

count = 0

# Strips the newline character
for line in lines:
    count += 1
    print("Line{}: {}".format(count, line.strip()))

Output

Line1: You
Line2: are
Line3: Wizard
Line4: Harry

And the same output will be written inside the app.txt file in the same format.

To read all the lines from a given file, you can use the Python readlines() function.

That’s it for today’s readlines() function.

See also

Python read file into list

Python file read

Python file handling

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.