Python Program Read a File Line by Line Into a List Ad Sponsored

ⓘ Sponsored by

Reading a file line by line into a list implies the following operations :

  1. Read a file
  2. Storing its contents in a list, with each line of the file being an element of the list.


Python Code :

The below Python program reads a file line by line and stores each line as an element in a list:

# Open the file
filename = "example.txt"
with open(filename) as file:
    # Use readlines() to read all the lines into a list
    lines = file.readlines()
# Print the list

In this program, we first open the file using the open() function and store the file object in the variable file. We then use the readlines() method to read all the lines in the file and store them in the list lines. Finally, we print the list to verify that we have successfully read the file.

Note that the readlines() method includes the newline character (\n) at the end of each line, so you may want to strip that off using the strip() method if you’re working with the lines in your program. Ad Sponsored

ⓘ Sponsored by