How to read a file line-by-line into a list?

To read a file line-by-line into a list, you can use the following approach:

with open('file.txt', 'r') as f:
    lines = [line.rstrip('\n') for line in f]

This will open the file in reading mode ('r'), and then use a list comprehension to read the file line by line, stripping the newline character at the end of each line. The result will be a list where each element is a line from the file.

Watch a course Python - The Practical Guide

You can also use a for loop to accomplish this:

lines = []
with open('file.txt', 'r') as f:
    for line in f:
        lines.append(line.rstrip('\n'))