How to Read Text File Into List in Python?

Last Updated : 27 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, reading a text file into a list is a common task for data processing. Depending on how the file is structured—whether it has one item per line, comma-separated values or raw content—different approaches are available. Below are several methods to read a text file into a Python list using the file data.txt as an example.

Using readline()

readlines() method reads all lines from the file and returns them as a list of strings. Each line includes the newline character \n at the end.

Python
with open('data.txt', 'r') as file:
    a = file.readlines()

print(type(a), a)

Output

<class 'list'> ['Hello geeks,\n', 'Welcome to geeksforgeeks \n']

Explanation: readlines() method reads the whole file and returns a list where each element is a line, including newline characters. This list is stored in a.

Using read().splitlines()

This method reads the entire file content as a string, then splits it into a list of lines without the newline characters.

Python
with open('data.txt', 'r') as file:
    a = file.read().splitlines()

print(type(a), a)

Output

<class 'list'> ['Hello geeks,', 'Welcome to geeksforgeeks ']

Explanation: read().splitlines() reads the entire file as a string and splits it into a list of lines without newline characters.

Using list comprehension

If your file contains numbers, you can read each line, strip whitespace, and convert it to an integer using a list comprehension.

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

print(type(a), a)

Output

<class 'list'> [1, 2, 3, 4, 5]

Explanation: This code reads each line from the file, removes any extra spaces, converts the line to an integer and stores all these integers in a list a.

Using list constructor

list() function can take the file object directly and convert its lines into a list. This method behaves similarly to readlines().

Python
with open('data.txt', 'r') as file:
    a = list(file)

print(type(a), a)

Output

<class 'list'> ['Hello geeks,', 'Welcome to geeksforgeeks ']

Explanation: This code converts the file object directly into a list, where each element is a line from the file (including newline characters).


Next Article
Article Tags :
Practice Tags :

Similar Reads