Open In App

Count Vowels, Lines, Characters in Text File in Python

Last Updated : 22 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

  1. Open the File: Use Python’s open() function in read mode to access the text file.
  2. Initialize Counters: Define three variables—vowel, line, and character—to track the number of vowels, lines, and characters, respectively.
  3. Define a Vowel List: Create a list of vowels to easily check whether a character is a vowel or not.
  4. Track Newlines: When encountering the newline character (\n), increment the line counter to keep track of the number of lines in the file.
  5. 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:



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg