Program to read a file line by line and store it in a list

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
  1. Set result_list blank list variable.
  2. Open the file with context manager with read mode.
  3. Initiate an infinite while loop.
  4. Read each line one by one.
  5. Check line is black or not and break the loop if it is blank.
  6. Append the lines in the result_list.
  7. 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.’]

 

 

get odd lines from files and append them to separate files.

find the longest word in a file.

Leave a Comment