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
- Open the first file by using open(“readcontent.txt”,”r”).
- Read the lines in the file using readlines().
- Create a count variable and assign its value equal to 0.
- Use a for loop to iterate over lines in the file.
- After each iteration add 1 to the count variable.
- 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