Home » How to Read Text File Into List in Python (With Examples)

How to Read Text File Into List in Python (With Examples)

by Erma Khan

You can use one of the following two methods to read a text file into a list in Python:

Method 1: Use open() 

#define text file to open
my_file = open('my_data.txt', 'r')

#read text file into list
data = my_file.read()

Method 2: Use loadtxt() 

from numpy import loadtxt

#read text file into NumPy array
data = loadtxt('my_data.txt')

The following examples shows how to use each method in practice.

Example 1: Read Text File Into List Using open()

The following code shows how to use the open() function to read a text file called my_data.txt into a list in Python:

#define text file to open
my_file = open('my_data.txt', 'r')

#read text file into list 
data = my_file.read()

#display content of text file
print(data)

4
6
6
8
9
12
16
17
19

Example 2: Read Text File Into List Using loadtxt()

The following code shows how to use the NumPy loadtxt() function to read a text file called my_data.txt into a NumPy array:

from numpy import loadtxt

#import text file into NumPy array
data = loadtxt('my_data.txt')

#display content of text file
print(data)

[ 4.  6.  6.  8.  9. 12. 16. 17. 19.]

#display data type of NumPy array
print(data.dtype)

float64

The nice thing about using loadtxt() is that we can specify the data type when importing the text file by using the dtype argument.

For example, we could specify the text file to be imported into a NumPy array as an integer:

from numpy import loadtxt

#import text file into NumPy array as integer
data = loadtxt('my_data.txt', dtype='int')

#display content of text file
print(data)

[ 4  6  6  8  9 12 16 17 19]

#display data type of NumPy array
print(data.dtype)

int64

Note: You can find the complete documentation for the loadtxt() function here.

Additional Resources

The following tutorials explain how to read other files in Python:

How to Read CSV File with NumPy
How to Read CSV Files with Pandas
How to Read a Text File with Pandas

Related Posts