Python Read Text File into List Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Read a Text File in Python?
- How to Append Text or Lines to a Text File in Python?
- Python Generate Text File from List Example
- Python Create Text File If Not Exists Example
- Python Create Text File in Specific Directory Example
- How to Create Multiline Text File in Python?
- Python Create an Empty Text File Example
- How to Create Text File in Python?
- Python List Add Element at Beginning Example
- How to Add Element at Specific Index in Python List?
- How to Find Sum of All Elements in List in Python?
- How to Count Number of Elements in a List in Python?