Python Program to Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
Beginner · File handling · CBSE class 12 practical list
This program reads a text file and counts four things: vowels (a, e, i, o, u), consonants (all the other letters), uppercase letters and lowercase letters. Spaces, digits and punctuation are not letters, so they are skipped. It is one of the standard file handling programs in the CBSE class 12 practical list.
Program
Vowels: 10 Consonants: 23 Uppercase letters: 10 Lowercase letters: 23
How it works
- The program writes two lines to
story.txtfirst, then reads the whole file intotextwithf.read(). - The loop looks at one character at a time, and
ch.isalpha()lets only letters through, so the digits in 12, the spaces, the full stop and the newlines are ignored. ch.lower() in "aeiou"catches both small and capital vowels, and every other letter is a consonant.- Separately,
ch.isupper()decides whether the letter is uppercase or lowercase, so each letter is counted twice: once as a vowel or consonant, and once by its case. - This sample file has 33 letters: 10 vowels and 23 consonants, and also 10 uppercase and 23 lowercase letters.
Another way to write it
Counting digits, spaces and other characters too
Digits: 2 Spaces: 3 Other characters: 2
Some versions of this question also ask for digits, spaces and special characters. isdigit() and a check for " " handle the first two, and the newline at the end of the line is left out on purpose.
Try it yourself
Add a fifth counter for digits, so the 1 and the 2 in "Class 12" are counted too.
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 Vowels, Consonants, Uppercase and Lowercase Letters
- Count Words in a Text File
- Count the Frequency of Each Character in a String
- Read a Text File and Separate Words with #
- 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
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises