How to Read a Text File Into a List in Python

Muhammad Waiz Khan Feb 02, 2024
  1. Read a Text File to List in Python Using read().split() on File Object Returned by open() Function
  2. Read a Text File to List in Python Using loadtxt Function of NumPy Library
  3. Read a Text File to List in Python Using csv.reader() Function
How to Read a Text File Into a List in Python

This tutorial will look into multiple methods to load or read a text file into a Python list. It includes using the read().split() function on file object returned by the open() function, the loadtxt function of NumPy library, and csv.reader function to load a text file and divide it into separate elements in the list.

Read a Text File to List in Python Using read().split() on File Object Returned by open() Function

Code example given below shows how we can first read a text file using open and then split it into an array using read().split() functions with , as the delimiter.

Suppose the content of the text file file.txt is below.

1,2,321,355,313

Code:

with open("file.txt", "r") as tf:
    lines = tf.read().split(",")

for line in lines:
    print(line)

Output:

1
2
321
355
313

The argument in the split() function, , in the example, specifies the delimiter in the text file.

Read a Text File to List in Python Using loadtxt Function of NumPy Library

Code example given below shows how we can use the loadtxt function of the NumPy library to load and split the text file into an array using the delimiter parameter.

from numpy import loadtxt

lines = loadtxt("file.txt", delimiter=",")
for line in lines:
    print(line)

Output:

1.0
2.0
321.0
355.0
313.0

Read a Text File to List in Python Using csv.reader() Function

csv module is typically used to process the CSV file but could also be used to process the text file.

The reader function of the csv module reads the given file and returns a _csv.reader object. We can convert the _csv.reader object to the list by applying the list() function.

Be aware that the converted list is a 2D array even if the file has only one line; therefore, we need to get the 1D list using the index [0].

import csv

with open("file.txt") as f:
    line = csv.reader(f, delimiter=",")

print(list(line)[0])

Output:

['1', '2', '321', '355', '313']

Related Article - Python List

Related Article - Python File