How to Read Text File into List in Python?

22-Dec-2022

.

Admin

How to Read Text File into List in Python?

Hi Dev,

This simple article demonstrates of how to read text file into list in python. This tutorial will give you simple example of python read text file into list of lists . I’m going to show you about how to open text file as a list in python. if you want to see example of how to read text file into list in python then you are a right place. So, let's follow few step to create example of python read text file into list without newline.

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.

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 nicesnippets.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:

file content are: One, Two, Three, Four, Five

The list is: ['One', ' Two', ' Three', ' Four', ' Five']

#Python