Example 2: Using the rstrip()
In this example instead of using the splitlines() method rstrip() method is used. rstrip() method removes trailing characters. the trailing character given in this example is ‘\n’ which is the newline. for loop and strip() methods are used to split the file into a list of lines. The file is closed at the end.
Python3
# opening the file file_obj = open ( "examplefile.txt" , "r" ) # splitting the file data into lines lines = [[x.rstrip( '\n' )] for x in file_obj] 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.
Contact Us