Count the total number of uppercase characters in a file in Python

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

Problem Statement

Python program to count the total number of uppercase characters in a file.

Problem description

We need to read the contents of the file and then count the number of uppercase characters in the string found.

We will use the concepts of file handling in python to read the contents of a file and then count the number of characters that are uppercase.

Counting the uppercase character in a file

The following are the steps to count the uppercase character in a file:

  • Step 1: Open the file in read mode.
  • Step 2: Extract the data from file character by character.
  • Step 3: Check if the character is an uppercase,
    • Step 3.1: If the character is upperCase, increase the counter.
  • Step 4: print the count of upperCase characters.

Python program to count the uppercase character in a file

try:
    upperCount =0
    F=open("names.dat","r")
    while(True):
        data=F.read(1)
        
        if(data==""):
            break
        if (ord(data) >= 65 and ord(data) <= 90): 
                upperCount = upperCount +1
    print(data,end='')
        
    print("Total Upper Case:",upperCount)
except FileNotFoundError as e:
    print(e)
finally:
    F.close()

Contents of file: (names.dat)

File Handling in Python Programming Language

Output

Total Upper Case characters in file : 5

Explanation

In the above code, we have opened the file "names.dat" in read mode. And then read character by character from the file and check if its case, if it is uppercase then we have added one to upperCount variable that stores the count of uppercase characters. Then at the end, return the count of uppercase characters in the file.

Python file handling programs »

Comments and Discussions!

Load comments ↻





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