In this python file program, we will read a file line by line and store it in a list. Let’s consider we have readcontent.txt file with the below content. We will read a file line by line with the help of the below-given steps.
# ReadContent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Steps to solve the program
- Set result_list blank list variable.
- Open the file with context manager with read mode.
- Initiate an infinite while loop.
- Read each line one by one.
- Check line is black or not and break the loop if it is blank.
- Append the lines in the result_list.
- print the result_list.
result_list = []
# Read file with context manager
with open("ReadContent.txt", "r") as file:
while True:
# read all line one by one until it is blank.
line = file.readline()
# once receive blank line, then break the loop
if not line:
break
result_list.append(line)
print(result_list)
Output:
[‘Line1 : This is India.\n’, ‘Line2 : This is America.\n’, ‘Line3 : This is Canada.\n’, ‘Line4 : This is Australia.\n’, ‘Line5 : This is Africa.’]