Python Program to count number of digits in a text file

 Python Program to count number of digits in a text file

In this example, you will how to count number of digits present in a text file using python.




Logic and Explanation

For counting number of digits present in a text file using python we will first open the required text file in read mode in our python file. For this we have to write the below command. Here, the name of text file is "content.txt" and it is present in the same directory where this python file is present, so we just written "content.txt" otherwise you have to write the complete path of the file here.

f = open("content.txt","r")
Now, we will read the content of the file using the below command and will get the data or the text present in it in the form of a string and then we will count the number of digits from that string.

text = f.read()

This text variable is string that contains all the data present in the text file "content.txt". Now, for counting the digits we will create a variable count_digit.

count_digit = 0

Now, let's count the digits. So, for counting the number of digits present in a string we will iterate through all the characters of that string and will check the condition for each character whether it is digit or not. If it is a digit then we will add one to our count_digit variable otherwise we will not increase it's value. In this way, when we had passed through all the characters the value of count_digit variable will be equal to the number of digits present in file.


for char in text:
    if char.isdigit():
        count_digit += 1
print(count_digit)

Complete source code the question is given below. I hope the explanation and the logic of the program is clear to you. In case of any doubt, you can ask in the comments below.

Source Code


f = open("content.txt","r")
text = f.read()
count_digit = 0
for char in text:
    if char.isdigit():
        count_digit += 1
print(count_digit) f.close()

If you like the content, share it in your social media platforms so that we can help the maximum. If you have any query then feel free to ask in the comments below.
We are ready to help you.

Check Similar Programs Here - Python Programs - Question and Answers

Enjoy Coding!!


For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment (0)

Previous Post Next Post