Python program to count total number of uppercase and lowercase characters in file

Python | Count uppercase and lowercase characters in a file: In this tutorial, we will learn how to count the total number of uppercase and lowercase characters in a file with its steps and program to implement it. By Shivang Yadav Last updated : July 05, 2023

Problem statement

Given a text file, we have to count the total number of uppercase and lowercase characters in a file.

Count total number of uppercase and lowercase characters

To count total number of uppercase and lowercase characters in file, you can use the concept of concept of file handling. File Handling in Python is reading and writing data from files.

We will first read characters from the file and then character check whether it is uppercase (using isupper() method ) or lowercase (using islower() method ) and count its respective number and print the count.

Python program to count total number of uppercase and lowercase characters in file

# Program to count total number of 
# uppercase and lowercase characters in file

# Start of try block
try:
    #Counter for characters...
    upperCount = 0
    lowerCount = 0

    F=open("file.dat","r")
    while(True):
        data=F.read(1)
        if(data==""):
            break
        if (data.isupper()): 
                upperCount = upperCount + 1
        elif (data.islower()): 
                lowerCount = lowerCount + 1
                
    print(data,end='')
        
    print("Total Upper Case:",upperCount)
    print("Total lower Case:",lowerCount)
except FileNotFoundError as e:
    print(e)
finally:
    F.close()

File : File.dat

Learn Programming At IncludeHelp

Output

Total Upper Case: 5
Total lower Case: 24

Python file handling programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.