How to Read Text File into List in Python?

Published On: 28/12/2022 | Category: Python


Hi Guys,

Today, I will let you know example of python read text file into list without newline. I would like to show you how to read text file into list in python. Here you will learn how to open text file as a list in python. if you have question about python read text file into list then I will give simple example with solution. Let's see bellow example python read text file into list of lists.

Python offers a variety of methods for reading text files into lists. I'll give you two examples of reading text files from lists in Python using the readlines() and read() functions. So let's look at the samples below.

So let's see bellow example:

Example 1: using readlines()

main.py
# Python read text file using readlines()
with open('readme.txt') as f:
    lines = f.readlines()
  
print(lines)
Output
['Hi Tuts-Station.com!\n', 'This is body\n', 'Thank you']

Example 2: using read()

main.py
# Read Text file using open()
textFile = open("readme.txt", "r")
fileContent = textFile.read()
print("The file content are: ", fileContent)
  
# Convert Content to List
contentList = fileContent.split(",")
textFile.close()
print("The list is: ", contentList)
Output
The file content are:  One, Two, Three, Four, Five
The list is:  ['One', ' Two', ' Three', ' Four', ' Five']

It will help you....

Happy Pythonic Coding!