Extract numbers from a text file and add them using Python

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files:

  • Text file (.txt extension)
  • Binary file (.bin extension)

Here we are operating on the .txt file in Python. Through this program, we can extract numbers from the content in the text file and add them all and print the result.

Approach

Reading the contents of the file, we will match the characters’ type against int. If the result of equality is true, then the number will be added to the number stored in the memory allocated to the variable ‘a’. We initiate the variable ‘a’ here with the value 0.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for writing
# to file
  
  
file = open('GFG.txt', 'w')
  
# Data to be written
data ='Geeks1 f2or G8e8e3k2s0'
  
# Writing to file
file.write(data)
  
# Closing file
file.close()

chevron_right


Using the above code, we opened a new file named ‘GFG’ in write mode. Using, the write() function we inserted the data allocated to the variable data in the memory. After this, we closed the file.

Reading from the above-created file and extracting the integers.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for reading
# from file
  
  
h = open('GFG.txt', 'r')
  
# Reading from the file
content = h.readlines()
  
# Varaible for storing the sum
a = 0
  
# Iterating through the content
# Of the file
for line in content:
      
    for i in line:
          
        # Checking for the digit in 
        # the string
        if i.isdigit() == True:
              
            a += int(i)
  
print("The sum is:", a)

chevron_right


Output:

The sum is: 24

The above program emphasizes on extracting the numbers from the content stored in the text file named ‘GFG’. Furthermore, the numbers are then added after typecasting and stored in the variable ‘a’.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.