Write a python program to count the number of lines in a text file

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.

It's a text file containing several text lines

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.

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post