Skip to main content

readlines()

The readlines() function in Python is a file method that reads all lines from a file and returns them as a list. Each line in the file is stored as a separate element in the list. This function is useful when you want to read the contents of a file line by line and store them in a data structure for further processing.

Parameter Values

This function does not accept any parameters.

Return Values

The readlines() method returns a list of strings, where each string is a line from the file.

How to Use readlines() in Python

Example 1:

The readlines() method reads all lines from a file and returns them as a list.

with open('data.txt', 'r') as file:
    lines = file.readlines()
    print(lines)
Example 2:

It can also be used with a loop to iterate over each line in the file.

with open('data.txt', 'r') as file:
    for line in file.readlines():
        print(line)
Example 3:

This method reads the entire file into memory, so it may not be suitable for very large files.

with open('data.txt', 'r') as file:
    all_lines = file.readlines()
    for line in all_lines:
        print(line)