Count Vowels, Lines, Characters in Text File in Python
Last Updated :
22 Mar, 2025
Improve
We are going to create a Python program that counts the number of vowels, lines, and characters present in a given text file.
Example:
Assume the content of sample_text.txt is:
Hello, this is a sample text file.
It contains multiple lines.
Counting vowels, lines, and characters.Output
Total number of vowels: 18
Total number of lines: 3
Total number of characters: 101
Step-by-Step Approach
- Open the File: Use Python’s
open()
function in read mode to access the text file. - Initialize Counters: Define three variables—
vowel
,line
, andcharacter
—to track the number of vowels, lines, and characters, respectively. - Define a Vowel List: Create a list of vowels to easily check whether a character is a vowel or not.
- Track Newlines: When encountering the newline character (
\n
), increment theline
counter to keep track of the number of lines in the file. - Iterate Through the File: Loop through each character in the file to count the vowels, characters (excluding vowels and newline characters), and lines based on the conditions defined.
Code Implementation
Below is the Python code to count vowels, lines, and characters in a text file:
def counting(filename):
txt_file = open(filename, "r")
vowel = 0
line = 0
character = 0
a = ['a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U']
for alpha in txt_file.read():
# Checking if the current character is vowel or not
if alpha in a:
vowel += 1
# Checking if the current character is not vowel or new line character
elif alpha not in a and alpha != "\n":
character += 1
# Checking if the current character is new line character or not
elif alpha == "\n":
line += 1
print("vowels ", filename, " = ", vowel)
print("New Lines ", filename, " = ", line)
print("characters ", filename, " = ", character)
counting('Myfile.txt')
Output:
Number of vowels in MyFile.txt = 23
New Lines in MyFile.txt = 2
Number of characters in MyFile.txt = 54
Explanation:
This Python code defines a counting() function that reads a file and counts the number of vowels, lines, and characters. It uses a loop to check each character, incrementing counters for vowels, non-vowel characters, and newlines. The results are printed to the console.
Text File:
