How to Read a File Line-by-Line into a List?

Better Stack Team
Updated on June 19, 2024

You can read a file line-by-line into a list in Python using a loop to iterate over each line in the file and appending each line to a list. Here's how you can do it:

 
# Open the file for reading
with open('filename.txt', 'r') as file:
    # Read lines from the file and store them in a list
    lines = file.readlines()

# Print the list of lines
print(lines)

In this code:

  • 'filename.txt' is the name of the file you want to read. Replace it with the actual filename.
  • 'r' specifies that the file should be opened in read mode.
  • file.readlines() reads all lines from the file and returns them as a list of strings, where each string represents one line of the file.
  • The list of lines is stored in the variable lines.

Now, the variable lines contains a list where each element corresponds to a line from the file.

If you want to remove the newline characters ('\\n') from each line, you can use the rstrip() method within a list comprehension like this:

 
# Open the file for reading
with open('filename.txt', 'r') as file:
    # Read lines from the file, remove trailing newline characters, and store them in a list
    lines = [line.rstrip('\\n') for line in file]

# Print the list of lines
print(lines)

This will give you a list where each line is stripped of any trailing newline characters.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.