Example 3: Using split()
We can use a for loop to iterate through the contents of the data file after opening it with Python’s ‘with’ statement. After reading the data, the split() method is used to split the text into words. The split() method by default separates text using whitespace.
Python3
with open ( "examplefile.txt" , 'r' ) as file_data: for line in file_data: data = line.split() print (data) |
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