Read a Text File Into a List in Python

  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

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']
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Append to Front of a List in Python
  • Count Unique Values in Python List
  • Related Article - Python File

  • What Is the Difference Between List Methods Append and Extend
  • Read Specific Lines From a File in Python