Editor

Python Program to Count the Lines in a File

Beginner · File handling

This program counts how many lines a text file has. It also counts the blank lines separately, because a line with nothing on it still counts as a line.

Program

count_lines_in_file.py
# Make a sample file to work on
with open("poem.txt", "w") as f:
f.write("Twinkle, twinkle, little star\n")
f.write("How I wonder what you are\n")
f.write("\n")
f.write("Up above the world so high\n")
f.write("Like a diamond in the sky\n")
total_lines = 0
blank_lines = 0
with open("poem.txt", "r") as f:
for line in f:
total_lines += 1
if line.strip() == "": # nothing on it but spaces or the newline
blank_lines += 1
print("Total lines:", total_lines)
print("Blank lines:", blank_lines)
print("Lines with text:", total_lines - blank_lines)
Output
Total lines: 5
Blank lines: 1
Lines with text: 4

How it works

  1. Five lines are written to poem.txt, and the third one is empty.
  2. The for loop reads the file one line at a time and adds 1 to total_lines for each line.
  3. line.strip() removes spaces and the newline, so a blank line becomes "" and is also counted in blank_lines.
  4. The lines with text are the total minus the blank lines, which gives 4 here.
  5. A last line with no newline after it is still read by the loop, so it is counted too.

Other ways to write it

Using readlines() and len()

Using readlines() and len()
# Make a sample file to work on
with open("poem.txt", "w") as f:
f.write("Twinkle, twinkle, little star\nHow I wonder what you are\n")
with open("poem.txt", "r") as f:
lines = f.readlines() # one list item per line
print("Number of lines:", len(lines))
Output
Number of lines: 2

readlines() returns a list with one string per line, so len() of that list is the number of lines. The whole file is held in memory, which is fine for small files.

Using sum()

Using sum()
# Make a sample file to work on
with open("poem.txt", "w") as f:
f.write("Twinkle, twinkle, little star\nHow I wonder what you are\nUp above the world so high\n")
with open("poem.txt", "r") as f:
count = sum(1 for line in f) # add 1 for every line read
print("Number of lines:", count)
Output
Number of lines: 3

sum(1 for line in f) adds 1 for each line while reading the file one line at a time, so it can count the lines of a huge file without storing them.

Try it yourself

Add a third counter for the lines that start with the letter "H".

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises