Count Vowels, Lines, Characters in Text File in Python
Last Updated :
22 Mar, 2025
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
, and character
—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 the line
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:
Python
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 al