How to convert each line in a text file into a list in Python

Converting each line in a text file results in a list of lists where each list is a line from the text file.

Solution for How to convert each line in a text file into a list in Python : You can use str.split() to convert each line in a text file into a list Use open(file, mode) with file as the pathname of the file and mode as “r” to open the file for reading. Create a for-loop to iterate through each line of the file. At each iteration, call str.strip() on the line to remove line breaks, and then call str.split() on the stripped line to create a list of the words in the line. Call list.append(line) with line as the previous list to add it to the initially empty list of lists. After, use file.close() to close file.

Use a list comprehension for a more compact implementation.

sample.txt


how-to-convert-each-line-in-a-text-file-into-a-list-in-python