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.
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)
['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.
['Hello geeks', 'Welcome to geeksforgeeks']
Please Login to comment...