Q:

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

0

 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now