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']
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?