Example 1: Using the splitlines()
The file is opened using the open() method where the first argument is the file path and the second argument is a string(mode) which can be ‘r’ ,’w’ etc.. which specifies if data is to be read from the file or written into the file. Here as we’re reading the file mode is ‘r’. the read() method reads the data from the file which is stored in the variable file_data. splitlines() method splits the data into lines and returns a list object. After printing out the list, the file is closed using the close() method.
Create a text file with the name “examplefile.txt” as shown in the below image which is used as an input.
Python3
# opening the file file_obj = open ( "examplefile.txt" , "r" ) # reading the data from the file file_data = file_obj.read() # splitting the file data into lines lines = file_data.splitlines() print (lines) file_obj.close() |
Output:
['This is line 1,', 'This is line 2,', 'This is line 3,']
How to Split a File into a List in Python
In this article, we are going to see how to Split a File into a List in Python.
When we want each line of the file to be listed at consecutive positions where each line becomes an element in the file, the splitlines() or rstrip() method is used to split a file into a list. Let’s see a few examples to see how it’s done.