Open In App

How to Read Text File Into List in Python?

In this article, we are going to see how to read text files into lists in Python.

File for demonstration:



Example 1: Converting a text file into a list by splitting the text on the occurrence of ‘.’.

We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line(‘/n’) with ‘ ‘ and split the text further when ‘.’ is seen using the split() and replace() functions. 



read(): The read bytes are returned as a string. Reads n bytes, or the full file if no n is given.

Syntax: fileobject.read(size)

split(): The split() method creates a list from a string. The separator can be specified; the default separator is any whitespace.

Syntax: string.split(separator, maxsplit)

replace(): The replace() method substitutes one phrase for another.

Syntax: string.replace(previous_value, value_to_be_replaced_with, count)

Code:




# opening the file in read mode
my_file = open("file1.txt", "r")
  
# reading the file
data = my_file.read()
  
# replacing end of line('/n') with ' ' and
# splitting the text it further when '.' is seen.
data_into_list = data.replace('\n', ' ').split(".")
  
# printing the data
print(data_into_list)
my_file.close()

Output:

['Hello geeks Welcome to geeksforgeeks']

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

The same process as before but we don’t replace any string here.




# opening the file in read mode
my_file = open("file1.txt", "r")
  
# reading the file
data = my_file.read()
  
# replacing end splitting the text 
# when newline ('\n') is seen.
data_into_list = data.split("\n")
print(data_into_list)
my_file.close()

Output:

['Hello geeks', 'Welcome to geeksforgeeks']

Article Tags :