How to Read a File Line-By-Line Into a Python List?
To read a file line-by-line into a Python list, you can use the following code:
with open(filename) as f:
lines = f.readlines()
This code opens the specified file (filename
) in read mode and uses a context manager (with
) to ensure that the file is properly closed after it is read. Then, it calls the readlines()
method on the file object to read all the lines of the file into a list (lines
), where each line is a separate element in the list.
You can then process the lines in the list as needed. For example, you could print each line by looping over the list:
for line in lines:
print(line)
Note that the readlines()
method includes the newline character (\n
) at the end of each line, so you may need to strip this character using the strip()
method if you want to clean up the text. For example, to create a list of the file's lines without newline characters, you can use the following code:
with open(filename) as f:
lines = [line.strip() for line in f.readlines()]
This code creates a list comprehension that strips the newline character (strip()
) from each line in the list returned by readlines()
.