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

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

This code will read the entire file into memory:

with open(filename) as file:
    lines = file.readlines()

If you want to remove all whitespace characters (newlines and spaces) from the end of each line, use this instead:

with open(filename) as file:
    lines = [line.rstrip() for line in file]

(This avoids allocating an extra list from file.readlines().)

If youre working with a large file, then you should instead read and process it line-by-line:

with open(filename) as file:
    for line in file:
        print(line.rstrip())

In Python 3.8 and up you can use a while loop with the walrus operator like so:

with open(filename) as file:
    while line := file.readline():
        print(line.rstrip())

See Input and Ouput:

with open(filename) as f:
    lines = f.readlines()

or with stripping the newline character:

with open(filename) as f:
    lines = [line.rstrip(n) for line in f]

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

This is more explicit than necessary, but does what you want.

with open(file.txt) as file_in:
    lines = []
    for line in file_in:
        lines.append(line)

Leave a Reply

Your email address will not be published. Required fields are marked *