How To Convert A Text File Into A List In Python

In this tutorial, we will learn how to convert a text file into a list in Python. This is a useful technique when working with large amounts of data or analyzing text from a file.

Being able to convert the contents of a file into a Python list allows us to perform operations on the data, such as sorting, searching, and filtering.

Step 1: Open the Text File

First, you need to have a text file that you would like to convert into a list. We’ll use a hypothetical file named “example.txt” for this tutorial. Here is the content of this file:


To begin, we need to open the text file in Python using the open() function. This function takes two arguments: the file name (as a string) and the mode in which to open the file (also a string). In our case, we’ll use the 'r' mode for reading.

Step 2: Read the Contents of the File

Next, we will read the contents of the file using the read() method of the file object.

This will read the entire contents of the file into a single string.

Step 3: Split the String into a List

Now that we have the contents of the file as a string, we need to split it into a list. We can do this using the splitlines() method, which splits the string at line breaks (\n) and returns a list of lines.

Step 4: Close the File

We are now done reading the file, so it’s important to close it using the close() method of the file object. This frees up any system resources tied to the file.

Step 5: Display the Result

Finally, let’s print the resulting list of lines to the screen to see the outcome of our code.

The output will be:

['Apple', 'Banana', 'Cherry', 'Date', 'Fig', ' Grape']

Full Code

Here is the complete code for this tutorial:


In this tutorial, we learned how to convert a text file into a list in Python. This technique can be extremely helpful when working with large datasets or analyzing the contents of a file. By following these simple steps, you can now easily convert a text file into a list using Python.