You can read a list from file using file.read() function and string.split() function in Python. Where file.read() 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 = fileobject.read(size) 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 = txt_file.read()
res = file_content.split(",")
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() print(content_list)
Converting a text file into a list by splitting the text on the occurrence of newline (‘\n’ )
my_file = open("file1.txt", "r") data = my_file.read() data_into_list = data.split("\n") print(data_into_list) my_file.close()
Do comment if you have any doubts or suggestions on this Python file topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.