Example 5: Using list comprehension
Python list comprehension is a beautiful way to work with lists. list comprehensions are powerful and they have shorter syntax. Furthermore, list comprehension statements are generally easier to read.
To read the text files in previous examples, we had to use a for loop. Using list comprehension, we can replace ours for loop with a single line of code.
After obtaining the data through list comprehension, the split() is used to separate the lines and append them to a new list. let’s see an example to understand.
Python3
with open ( "examplefile.txt" , 'r' ) as file : data = [line.strip() for line in file ] print (data) # iterating through data for line in data: print (line.split()) |
Output:
['This is line 1,', 'This is line 2,', 'This is line 3,'] ['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