Skip to content

Python read list from file

  • by

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()
print(file_content)

res = file_content.split(",")
txt_file.close()
print(res)

Output:

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()
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)

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 *