Open In App

Extract numbers from a text file and add them using Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Method 1: 

Python3




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


Time complexity: O(1) – writing to a file is a constant time operation.
Auxiliary space: O(1) – the space used by the program is constant, as it only opens, writes and closes the file.

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.

Python3




# Python program for reading
# from file
 
 
h = open('GFG.txt', 'r')
 
# Reading from the file
content = h.readlines()
 
# Variable 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

Time complexity: O(n*m), where n is the number of lines in the file and m is the maximum number of characters in a line.
Auxiliary space: O(1), as only one variable “a” is used to store the sum.

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

Method 2: This approach uses the re module to extract all the numbers from the content of the file. The regular expression \d+ is used to match one or more digits. The findall function is used to extract all the numbers as a list of strings. Finally, the map function is used to convert each string to an int and sum is used to add all the numbers.

Python3




# code
print("GFG")
import re
 
# 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()
def extract_and_add_numbers(file_name):
    # Open the file in read mode
    with open(file_name, 'r') as file:
        # Read the contents of the file
        content = file.read()
 
        # Extract all the numbers from the content
        numbers = re.findall(r'\d+', content)
 
        # Convert the extracted numbers to int and sum them
        result = sum(map(int, numbers))
 
        return result
 
# Example usage
file_name = "GFG.txt"
result = extract_and_add_numbers(file_name)
print("The sum of the numbers in the file is:", result)
#This code is contributed by Edula Vinay Kumar Reddy


Output

GFG
The sum of the numbers in the file is: 24

Time complexity: O(n), where n is the number of characters in the file.
Auxiliary Space: O(m), where m is the number of digits in the file.



Last Updated : 20 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads