9 ways to convert file to list in Python

Python List

In this post, we are going to learn 9 ways to convert file to list in Python. We will learn all these ways with code examples. We will take a sample text file with some data in it and then we will load the file data to a Python list.

So let us begin with our tutorial.

Sample File : samplefile.txt’


This is the sample file that we are using in the code example. It exists in the current directory.

Welcome to devenum.
we are exploring about list.
How are you.
good to see you again.

1. Pathlib to Convert text file to list Python


In Python 3.4. , we can use the Pathlib module to convert a file to a list. This is a simple way to convert a file to a list. In this example, we will use the read_text() method to read the file and the splitlines() method for the splitting of lines.

Program Example

from pathlib import Path
filepath = Path('samplefile.txt')

lines = filepath.read_text().splitlines()  
print(lines)

Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

2. For Loop to split file to list Python


In this example, We are iterating over each line of a file using for loop and appending each line to the list by removing the special new character(\n) using the strip() method.

Program Example

with open("samplefile.txt") as file:
    listfile = []
    for line in file:
     listfile.append(line.strip())
    print(listfile)



Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

3. File.Read() to put each line in list Python


In this example, We are using the file built-in open() method to open the file, Read()method to read the contents of the file. Then we are using the split() method to remove new line character(\n) at end of each line.

Program Example

with open("samplefile.txt") as file:
    filecontents = file.read().split('\n')
    
    print(filecontents)

Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

4. Readline() to create list from text file


The file readlines() method returns a list of file lines, separated by the newline character(\n). So here we are iterating over lines of a file and using the strip() method to remove the newline character(\n) end of each line.

Program Example

with open("samplefile.txt") as file:
     filecontents = file.readlines()
     filecontents = [line.strip() for line in filecontents]
     print(filecontents)

Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

5. Using iter() to read and storetext file in list Python


In this example, We are iterating over the file contents using the iter() method. Also to iterate over each line of a file we are using the next() method. Then we are Appending it to empty list(list_lines) using append() method.The strip() method is used to remove newline character(\n) at end of each line.

Program Example

with open("samplefile.txt") as file:

 list_lines = []
 while True:
    try:          
        list_lines.append(next(iter(file)).strip())
    except StopIteration:
        break
print(list_lines)


Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

6. Python read text file line by line into list Python


In this example, We will use a tuple to convert a file to a list. It returns the lines of the file as a list. Let us understand this as shown in the example below.

Program Example

lines = tuple(open("samplefile.txt", 'r'))
print(lines)

Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

7. OS module to convert each line in text file into list in Python


We can use the os module fd.open() function that returns an open file object connected to file description fd. The descriptor is get by using os.open().

Program Example

import os

file = os.open("samplefile.txt", os.O_RDONLY)

fileobj = os.fdopen(file)
content = fileobj.readlines()
content = [line.strip() for line in content]
print(content)

Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

9. Fileinput module to put file to list Python


In this example, we are using the fileinput module. It is used to iterate over multiple files or a list of files.

We are iterating over the file using the input() method and appending each line to list and removing new line characters using the strip() method.

Program Example

import fileinput

list_lines=[]
for line in fileinput.input(files=["samplefile.txt"]):
    list_lines.append(line.strip())
print(list_lines)

Output

['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']

Summary :

We have explored 9 ways to convert files to a list with code examples. Using File function, OS Module,pathlib module, Fileinput Module.