Python Read Text File into List Example

By Hardik Savani October 30, 2023 Category : Python

Hello Dev,

In this tutorial, I will show you python read text file into list. you can understand a concept of python read text file into list without newline. If you have a question about how to read text file into list in python then I will give a simple example with a solution. This post will give you a simple example of how to open text file as a list in python. Let's see below example python read text file into list of lists.

There are many ways to read text file into lists in python. i will give you two examples using readlines() function and read() function to read text file in list in python. so let's see the below examples.

Without any further ado, let's see the below code examples below one by one.

You can use these examples with python3 (Python 3) version.

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 ItSolutionstuff.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']

I hope it can help you...

Tags :
Shares