Method 1: Using the readlines() method
Example
txt_file = open(“apple.txt”, “r”)
content_list = txt_file.readlines()
print(content_list)
Output
[‘apple, microsoft, amazon, alphabet, facebook’]
Method 2: Using the file.read() method with string.split() method
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)
Output
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
11
21
19
18
46
Now, we can load this Txt file in our Python file.
from numpy import loadtxt
data = loadtxt(“app.txt”)
print(data)
Output
[11. 21. 19. 18. 46.]
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)
Output
[’11’, ’21’, ’19’, ’18’, ’46’]
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)
Output
[’11’, ’21’, ’19’, ’18’, ’46’]