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

Sometimes, we want to read a file line-by-line into a list with Python.

In this article, we’ll look at how to read a file line-by-line into a list with Python.

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

To read a file line-by-line into a list with Python, we can use the use the with statement and the open function.

For instance, we write:

foo.txt

foo
bar
baz
filename = './foo.txt'
with open(filename) as file:
    for line in file:
        print(line.rstrip())

We set filename to the path of foo.txt.

Then we call open with filename to read the file into file in the with statement.

Then we loop through each line in the file.

And we call line.rstrip to trim the whitespaces at the end of each line.

Since we use the with statement, the file will be closed automatically after we’re done reading it.

Therefore, we see:

foo
bar
baz

printed.

Conclusion

To read a file line-by-line into a list with Python, we can use the use the with statement and the open function.