Alex Rivera | Logout

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

Asked 2010-07-18T22:25:01.410
2023

How do I read every line of a file in Python and store each line as an element in a list?

I want to read the file line by line and append each line to the end of the list.

Edit
Report

1 Answer

320

This will yield an "array" of lines from the file.

lines = tuple(open(filename, 'r'))

open returns a file which can be iterated over. When you iterate over a file, you get the lines from that file. tuple can take an iterator and instantiate a tuple instance for you from the iterator that you give it. lines is a tuple created from the lines of the file.

answered 2010-07-18T22:27:24.383

Your Answer