Try this one, it should store each text file to an element in the list.
textfile_list = ['file1.txt', 'file2.txt', 'file3.txt']
list = []
for f in textfile_list:
file_text = open(f, 'r').read()
list.append(file_text)
print(list[0])
print(list[1])
print(list[2])
Last Updated : 19 Dec, 2021,GATE CS 2021 Syllabus
Output:
['Hello geeks Welcome to geeksforgeeks']
Another way to achieve the same thing is using a for loop. In each iteration, you can read each line of f object and store it in content_list as shown in the example above.,To understand this example, you should have the knowledge of the following Python programming topics:,In this example, you will learn to read a file line by line into a list.,First, open the file and read the file using readlines().
Let the content of the file data_file.txt
be
honda 1948 mercedes 1926 ford 1903
Source Code
with open("data_file.txt") as f:
content_list = f.readlines()
# print the list
print(content_list)
# remove new line characters
content_list = [x.strip() for x in content_list]
print(content_list)
Output
['honda 1948\n', 'mercedes 1926\n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']
readlines() is a built-in method in Python used to read a file line by line and then store each line in a list. ,I hope that after reading this article you can read files line by line and then store the elements in a list such that each line represents an element of the list. Please subscribe and stay tuned for more interesting articles!,string.rstrip() is a built-in function in Python that removes all whitespaces on the right of the string (trailing whitespaces). Thus, we can use it to strip or separate elements out of each line and then store them in a list using the [] notation.,Problem: How to read every line of a file in Python and store each line as an element in a list?
Output:
['Jeff Bezos', 'Bill Gates', 'Mark Zuckerberg', 'Bernard Arnault & family', 'Mukesh Ambani', 'Steve Ballmer', 'Warren Buffett', 'Larry Page', 'Elon Musk', 'Sergey Brin']
We are going to use the readlines()
method to read the file line by line while the strip()
method is used to get rid of the new line character '\n'
while storing the elements in the list. Let us have a look at the following program to visualize how we can solve our problem using the above-mentioned methods.
with open('test.txt') as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line li = [x.strip() for x in content] print(li)
Example:
with open('test.txt') as f:
lines = [line.rstrip() for line in f]
print(lines)
Example:
from pathlib
import Path
p = Path('test.txt')
lines = p.read_text().splitlines()
print(lines)
If you want to learn more about list comprehensions, please have a look at our blog tutorial here. Now let us have a look at a one-line solution to our problem using list comprehension.
print([line.rstrip() for line in open('test.txt')])