Join our newsletter for the latest updates.

Python Program Read a File Line by Line Into a List

In this example, you will learn to read a file line by line into a list.

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using readlines()

The content of the file data_file.txt is

honda 1948
mercedes 1926
ford 1903

Source Code

with open("data_file.txt") as f:
    content_list = f.readlines()

# print the list
print(content_list)

# remove new line characters
content_list = [x.strip() for x in content_list]
print(content_list)

Output

['honda 1948\n', 'mercedes 1926\n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']

readlines() returns a list of lines from the file.


Example 2: Using for loop and list comprehension

with open('data_file.txt') as f:
    content_list = [line for line in f]

print(content_list)

# removing the characters
with open('data_file.txt') as f:
    content_list = [line.rstrip() for line in f]

print(content_list)

Output

['honda 1948\n', 'mercedes 1926\n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']