Extract numbers from a text file and add them in Python

In Python, we can extract numbers from a text file and then get their sum by adding them. As we know, Python provides us with many file handling options i. e. read, write, etc. In this tutorial, we will see how to operate on numbers hidden in a text file using some of the file handling techniques.

Let’s create a file ‘codespeedy.txt’ with the following content:

c1o2de3sp4eed5y

The program to create the above file has been given below.

f = open('codespeedy.txt', 'w+')

f.write('c1o2de3sp4eed5y')

f.close()

When we execute the above code, a file named ‘codespeedy.txt’ is created with the content given above. Now we need to write code that can extract all the numbers from this file and then add them.

Extracting numbers from the file and adding them

To do this, first, we open the file in reading mode. We iterate through the content using loops and find all integers using isdigit() method and then add them to the variable sum which was initialized as zero.

The below program implements the above approach in Python. See the code.

sum = 0

with open('codespeedy.txt', 'r') as f:
    for line in f:
        for char in line:
            if char.isdigit():
                sum = sum + int(char)
            
print(sum)

Output:

15

As you can see, we have got the output as 15 which is the sum of all the numbers in the string “c1o2de3sp4eed5y”. You can also change the name of the file passed in open() function and test the code with any other text file with numbers in it.

Thank you.

Also read: Print all Disarium numbers within given range in Python

Leave a Reply

Your email address will not be published. Required fields are marked *