Skip to content
Related Articles

Related Articles

Extract numbers from a text file and add them using Python
  • Last Updated : 29 Dec, 2020

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.




# 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()

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.






# 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)

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’.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :