25.5 C
London
Thursday, June 19, 2025
HomePandas in PythonInput/Output in PythonHow to Read Text File Into List in Python (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories