ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

Here, we are going to learn how to count the total number of uppercase characters in a file in Python?
Submitted by Shivang Yadav, on February 12, 2021

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.

Steps to count the uppercase characters 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.

Program to illustrate the solution of the problem

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

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.