Write a Python Program Read a File Line by Line Into a List

In Python, there are several ways to read a file line by line into a list.

In this tutorial, we will discuss one of the simplest ways to do it.


First, we need to open the file using the built-in open() function.

This function takes two arguments: the file name and the mode in which the file should be opened.

The most common modes are ‘r’ (read mode) and ‘w’ (write mode).

Since we want to read the file, we will use ‘r’ mode.

with open('file.txt', 'r') as file:

The with statement is used to ensure that the file is properly closed after it has been read.

This is done automatically and is considered good practice.

Next, we will use a for loop to read each line of the file and append it to a list.

Here is the complete code:

with open('file.txt', 'r') as file:
    lines = []
    for line in file:
        lines.append(line.strip())

In this code, we created an empty list lines to hold the lines of the file.

Then, we used a for loop to iterate over each line in the file.

The strip() method is used to remove any whitespace characters at the beginning and end of each line.

Finally, we appended the stripped line to the lines list.

Once the loop is complete, the lines list will contain all the lines of the file.

You can then print the list or use it in any other way you want.

Here is the complete code again, this time with an example file:

with open('example.txt', 'r') as file:
    lines = []
    for line in file:
        lines.append(line.strip())

print(lines)

Output:

['This is the first line.', 'This is the second line.', 'This is the third line.']

In conclusion, reading a file line by line into a list in Python is a simple process that involves opening the file, iterating over each line, and appending it to a list.

This technique is very useful when you need to process the lines of a file one at a time, and it can be adapted to many different use cases.