Skip to content

Python read list from file

  • by

You can read a list from file using function and string.split() function in Python. Where function to return the entire content of the file as a string and string.split() function to split a text file into a list.

string =
string.split(separator, maxsplit)

Python read list from file example

A simple example code read a comma-separated text file and split the string into the list.

txt_file = open("somefile.txt", "r")
file_content =

res = file_content.split(",")


Python read list from file

Use the readlines() method to get a list containing each line in the file as a list element.

txt_file = open("apple.txt", "r")

content_list = txt_file.readlines()

Converting a text file into a list by splitting the text on the occurrence of newline (‘\n’ )

my_file = open("file1.txt", "r")
data =
data_into_list = data.split("\n")

Do comment if you have any doubts or suggestions on this Python file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *