Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Print the Content of a Txt File in Python
Next article icon

Count Vowels, Lines, Characters in Text File in Python

Last Updated : 22 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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 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
Print the Content of a Txt File in Python

B

bansalshubhamcse21
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Python | Finding 'n' Character Words in a Text File
    This article aims to find words with a certain number of characters. In the code mentioned below, a Python program is given to find the words containing three characters in the text file. Example Input: Hello, how are you ? , n=3 Output: how are you Explanation: Output contains every character of th
    3 min read
  • Count Words in Text File in Python
    Our task is to create a Python program that reads a text file, counts the number of words in the file and prints the word count. This can be done by opening the file, reading its contents, splitting the text into words, and then counting the total number of words. Example 1: Count String WordsFirst,
    3 min read
  • Append Text or Lines to a File in Python
    Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutori
    3 min read
  • Print the Content of a Txt File in Python
    Python provides a straightforward way to read and print the contents of a .txt file. Whether you are a beginner or an experienced developer, understanding how to work with file operations in Python is essential. In this article, we will explore some simple code examples to help you print the content
    3 min read
  • Count the number of characters in a String - Python
    The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Let’s explore different approaches to accomplish this. Using len()len() i
    3 min read
  • Python - Test for Word construction from character list
    Given a List and a String, test if the string can be made from list characters. Examples: Input : test_list = ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k'], test_str = 'geeks4geeks' Output : True Explanation : String can be made according to character frequencies.Input : tes
    6 min read
  • Get number of characters, words, spaces and lines in a file - Python
    Given a text file fname, the task is to count the total number of characters, words, spaces, and lines in the file. As we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to calculate the total number of characters, words, spaces, and line
    5 min read
  • Python - Count occurrences of each word in given text file
    Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the w
    4 min read
  • Python Program to Count characters surrounding vowels
    Given a String, the task is to write a Python program to count those characters which have vowels as their neighbors. Examples: Input : test_str = 'geeksforgeeksforgeeks' Output : 10 Explanation : g, k, f, r, g, k, f, r, g, k have surrounding vowels. Input : test_str = 'geeks' Output : 2 Explanation
    3 min read
  • Specific Characters Frequency in String List-Python
    The task of counting the frequency of specific characters in a string list in Python involves determining how often certain characters appear across all strings in a given list. For example, given a string list ["geeksforgeeks"] and a target list ['e', 'g'], the output would count how many times 'e'
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences