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
Total lines: 5 Blank lines: 1 Lines with text: 4
How it works
- Five lines are written to
poem.txt, and the third one is empty. - The
forloop reads the file one line at a time and adds 1 tototal_linesfor each line. line.strip()removes spaces and the newline, so a blank line becomes""and is also counted inblank_lines.- The lines with text are the total minus the blank lines, which gives 4 here.
- 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()
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()
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.
Related programs
- Count Words in a Text File
- Count the Characters in a File
- Display Lines Starting with T in a Text File
- Read a File Line by Line
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
All Python programs · CBSE class 12 practical file · Python exercises