How to add items to a list from a text file in Python
Hello Python learners, today in this tutorial I will show you how to add items to a list in from a text file in python. Or you can say, with this tutorial you will learn how to add elements to a list from a text file line by line.
So this tutorial will consist of:
- Read a text file in Python.
- Then append each line from the text file to your list using a for loop.
Add elements to a list from a text file each line as a new element in Python
Let’s start with our example text file.
This is a text file And we are going to add these lines to a list in Python
Now we are about to add all the lines one by one to a Python list from this text file.
Our first step will be to read all the lines of the text file. That can be done with the following code:
my_file = open('my_text_file.txt') all_the_lines = my_file.readlines()
Remember: In this case the text file and my python program file, i.e codespeedy.py both are in the same directory. If your text file is located in some other directory or folder then you must need to mention the location or path of your text file here: my_file = open(‘path_of_your_file’)
Till now we have read the lines from our text file. Now, the next part is to append all the lines one by one to our list.
So where is the list? Don’t worry let’s just create an empty list and then we will append each and every line from our text file one by one.
my_file = open('my_text_file.txt') all_the_lines = my_file.readlines() items = 
items is our list variable now. We will append lines from the text file in this list one by one using a for loop.
Final Python program to add each line from the text file to our Python list:
my_file = open('my_text_file.txt') all_the_lines = my_file.readlines() items =  for i in all_the_lines: items.append(i) print(items)
$ python codespeedy.py ['This\n', 'is\n', 'a text\n', 'file\n', 'And we\n', 'are going to\n', 'add\n', 'these\n', 'lines\n', 'to a list\n', 'in Python']
Now you can see we have imported all the lines from our text file to our Python list.
But hey wait. Why the \n at the end of each element in Python list?
Because in the text file there are new lines. And Python read the text file properly.
But you may ask how to get read of the last character \n of list items?
Yes, I have a solution for it too. Just follow this tutorial as well: How to remove \n from list elements in Python – last character new line