Read a File into a List in Python

  • Post category:List

Reading a file into a list is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to read a file and store its contents into a list efficiently.

Example 1:

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

Output: [‘This is line 1.’, ‘This is line 2.’, ‘This is line 3.’]

Example 2:

with open('numbers.txt', 'r') as file:
    numbers = [int(line.strip()) for line in file]
print(numbers)

Output: [1, 2, 3, 4, 5]