Introduction
A text file contains a sequence of lines which are formed by a number of letters, numbers, symbols, etc. The total number of lines can be calculated manually but if the file size is huge then it would be a difficult task. To solve this problem we'll take the help of programming.
In this section, we'll write a python program to count the number of lines in a text file. Please check file handling in python if you don't familiar with working with files in python.
Example
This is what our text file looks like.
Code
file = open("file.txt", "r")
# Reading the file content
content = file.read()
content = content.split("\n")
# Declaring the count variable
count = 0
for ix in content:
# Checking if the line is empty or not
# if empty then the count variable will not increase
if ix:
count += 1
print("The number of lines in the file is: ", count)
# Closing the file
file.close()
Output
The number of lines in that file is: 12
Exercise
☛Count the total number of spaces in the lines in a text file.