Program to count the number of lines in a file

In this python file program, we will count the number of lines in a file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content. 

				
					Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”,”r”).
  2. Read the lines in the file using readlines().
  3. Create a count variable and assign its value equal to 0.
  4. Use a for loop to iterate over lines in the file.
  5. After each iteration add 1 to the count variable.
  6. Print the output.
				
					# Open file in read mode
file=open("readcontent.txt","r")
# Read lines
lines= file.readlines()
# Create count variable
count = 0
# Iterate over lines
for line in lines:
# Add 1 to count for each line
    count += 1
# Print output
print("Total number of lines in the file: ",count)
				
			

Output : 

Total number of lines in the file: 8


compare two files.

get the file size of a file.

Leave a Comment