ItSolutionStuff.com

Python Read Text File into List Example

By Hardik Savani • October 30, 2023
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: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Read a Text File in Python?

Read Now →

How to Append Text or Lines to a Text File in Python?

Read Now →

Python Generate Text File from List Example

Read Now →

Python Create Text File If Not Exists Example

Read Now →

Python Create Text File in Specific Directory Example

Read Now →

How to Create Multiline Text File in Python?

Read Now →

Python Create an Empty Text File Example

Read Now →

How to Create Text File in Python?

Read Now →

Python List Add Element at Beginning Example

Read Now →

How to Add Element at Specific Index in Python List?

Read Now →

How to Find Sum of All Elements in List in Python?

Read Now →

How to Count Number of Elements in a List in Python?

Read Now →