- How to Read a File into List in Python
- Method 1: Using the readlines() method
- Example
- Method 2: Using the file.read() method with string.split() method
- Example
- Method 3: Using the np.loadtxt() method
- Example
- Method 4: Using the list comprehension
- Example
- Method 5: Using for loop with strip() method
- Example
- Как прочитать текстовый файл в список в Python (с примерами)
- Пример 1: Чтение текстового файла в список с помощью open()
- Пример 2: Чтение текстового файла в список с помощью loadtxt()
- Дополнительные ресурсы
- 9 ways to convert file to list in Python
- Sample File : samplefile.txt’
- 1. Pathlib to Convert text file to list Python
- Program Example
- Most Popular Post
- 2. For Loop to split file to list Python
- Program Example
- 4. Readline() to create list from text file
- Program Example
- 5. Using iter() to read and storetext file in list Python
- Program Example
- 6. Python read text file line by line into list Python
- Program Example
- 7. OS module to convert each line in text file into list in Python
- Program Example
- 9. Fileinput module to put file to list Python
- Program Example
- Summary :
- Read a Text File Into a List in Python
- Read a Text File to List in Python Using read().split() on File Object Returned by open() Function
- Read a Text File to List in Python Using loadtxt Function of NumPy Library
- Read a Text File to List in Python Using csv.reader() Function
- Related Article — Python List
How to Read a File into List in Python
Method 1: Using the readlines() method
The easiest way to read a file into the list in Python is to use the “readlines()” method. The “readlines()” method returns a list containing each line in the file as a list element. It returns all the lines in the file as a list where each line is an item in the list object.
Example
txt_file = open("apple.txt", "r") content_list = txt_file.readlines() print(content_list)
['apple, microsoft, amazon, alphabet, facebook']
Method 2: Using the file.read() method with string.split() method
You can also use the “file.read()” function to return the entire file content as a string and use the string.split() function to split a text file into a list.
Example
Let’s define the apple.txt text file in the same directory as our Python program file.
apple, microsoft, amazon, alphabet, facebook
It is a comma-separated value inside the apple.txt file.
We will read this file using a “file.read()” function and split the string into the list.
txt_file = open("apple.txt", "r") file_content = txt_file.read() print("The file content are: ", file_content) content_list = file_content.split(",") txt_file.close() print("The list is: ", content_list)
The file content are: apple, microsoft, amazon, alphabet, facebook The list is: ['apple', 'microsoft', 'amazon', 'alphabet', 'facebook']
And you can see that we successfully read a file content into the list.
Method 3: Using the np.loadtxt() method
Another way is to use the “np.loadtxt()” function from the numpy module to read a text file into a NumPy array. Let’s say we have an app.txt file with the following contents.
Example
Now, we can load this Txt file in our Python file.
from numpy import loadtxt data = loadtxt("app.txt") print(data)
Method 4: Using the list comprehension
You can also use “list comprehension” to read the file and create a list of lines.
Example
with open("app.txt", "r") as file: lines = [line.strip() for line in file] print(lines)
Method 5: Using for loop with strip() method
You can also read the file line by line using a for loop and the “append()” function to append each line to a list.
Example
lines = [] with open("app.txt", "r") as file: for line in file: lines.append(line.strip()) print(lines)
Как прочитать текстовый файл в список в Python (с примерами)
Вы можете использовать один из следующих двух методов для чтения текстового файла в список в Python:
Способ 1: Используйте open()
#define text file to open my_file = open('my_data.txt', 'r') #read text file into list data = my_file.read()
Способ 2: использовать loadtxt()
from numpy import loadtxt #read text file into NumPy array data = loadtxt('my_data.txt')
В следующих примерах показано, как использовать каждый метод на практике.
Пример 1: Чтение текстового файла в список с помощью open()
В следующем коде показано, как использовать функцию open() для чтения текстового файла с именем my_data.txt в список в Python:
#define text file to open my_file = open('my_data.txt', 'r') #read text file into list data = my_file.read() #display content of text file print(data) 4 6 6 8 9 12 16 17 19
Пример 2: Чтение текстового файла в список с помощью loadtxt()
В следующем коде показано, как использовать функцию NumPy loadtxt() для чтения текстового файла с именем my_data.txt в массив NumPy:
from numpy import loadtxt #import text file into NumPy array data = loadtxt('my_data.txt') #display content of text file print(data) [ 4. 6. 6. 8. 9. 12. 16. 17. 19.] #display data type of NumPy array print(data. dtype ) float64
Хорошая вещь в использовании loadtxt() заключается в том, что мы можем указать тип данных при импорте текстового файла с помощью аргумента dtype .
Например, мы можем указать текстовый файл для импорта в массив NumPy как целое число:
from numpy import loadtxt #import text file into NumPy array as integer data = loadtxt('my_data.txt', dtype='int') #display content of text file print(data) [ 4 6 6 8 9 12 16 17 19] #display data type of NumPy array print(data. dtype ) int64
Примечание.Полную документацию по функции loadtxt() можно найти здесь .
Дополнительные ресурсы
Следующие руководства объясняют, как читать другие файлы в Python:
9 ways to convert file to list in Python
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)
['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']
Most Popular Post
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: filecontents = file.read().split('\n') print(filecontents)
['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)
['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)
['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)
['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)
['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)
['Welcome to devenum.', 'we are exploring about list.', 'How are you.', 'good to see you again.']
Summary :
We have explored 9 ways to conve9 ways to convert file to list in Python with code examples. Using File function, OS Module,pathlib module, Fileinput Module.
Read a Text File Into a List in Python
- Read a Text File to List in Python Using read().split() on File Object Returned by open() Function
- Read a Text File to List in Python Using loadtxt Function of NumPy Library
- Read a Text File to List in Python Using csv.reader() Function
This tutorial will look into multiple methods to load or read a text file into a Python list. It includes using the read().split() function on file object returned by the open() function, the loadtxt function of NumPy library, and csv.reader function to load a text file and divide it into separate elements in the list.
Read a Text File to List in Python Using read().split() on File Object Returned by open() Function
Code example given below shows how we can first read a text file using open and then split it into an array using read().split() functions with , as the delimiter.
Suppose the content of the text file file.txt is below.
with open("file.txt", "r") as tf: lines = tf.read().split(',') for line in lines: print(line)
The argument in the split() function, , in the example, specifies the delimiter in the text file.
Read a Text File to List in Python Using loadtxt Function of NumPy Library
Code example given below shows how we can use the loadtxt function of the NumPy library to load and split the text file into an array using the delimiter parameter.
from numpy import loadtxt lines = loadtxt("file.txt", delimiter=",") for line in lines: print(line)
Read a Text File to List in Python Using csv.reader() Function
csv module is typically used to process the CSV file but could also be used to process the text file.
The reader function of the csv module reads the given file and returns a _csv.reader object. We can convert the _csv.reader object to the list by applying the list() function.
Be aware that the converted list is a 2D array even if the file has only one line; therefore, we need to get the 1D list using the index [0] .
import csv with open("file.txt") as f: line = csv.reader(f, delimiter=',') print(list(line)[0])