The Wayback Machine - https://web.archive.org/web/20240717024332/https://www.geeksforgeeks.org/extract-numbers-from-a-text-file-and-add-them-using-python/
Open In App

Extract numbers from a text file and add them using Python

Last Updated : 20 Feb, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
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.



Similar Reads

Extract text from PDF File using Python
All of you must be familiar with what PDFs are. In fact, they are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. We will extract text from pdf files using two Pytho
3 min read
Python program to extract Email-id from URL text file
Prerequisite : Pattern Matching with Python Regex Given the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work. Example : Input : Hello This is Geeksforgeeks review-team@geeksforgeeks.org review-team@geeksforgeeks.org GfG is a portal for gee
1 min read
How to extract paragraph from a website and save it as a text file?
Perquisites: Beautiful soupUrllib Scraping is an essential technique which helps us to retrieve useful data from a URL or a html file that can be used in another manner. The given article shows how to extract paragraph from a URL and save it as a text file. Modules Needed bs4: Beautiful Soup(bs4) is a Python library used for getting data from HTML
2 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Extract and Add FLAC Audio Metadata using the mutagen module in Python
Audio metadata is information embedded into audio files to identify and label audio files. Metadata includes information like artist, genre, album and track number. This information is very essential for making music players and other related applications. Streaming platforms also use metadata to categorize music according to various filters like a
3 min read
Extract IP address from file using Python
Let us see how to extract IP addresses from a file using Python. Algorithm : Import the re module for regular expression.Open the file using the open() function.Read all the lines in the file and store them in a list.Declare the pattern for IP addresses. The regex pattern is : r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'For every element of the list sea
2 min read
How to extract Email column from Excel file and find out the type of mail using Pandas?
In this article, Let's see how to Extract Email column from an Excel file and find out the type of mail using Pandas. Suppose our Excel file looks like below given image, and then we have to store different type of emails in different columns of Dataframe. For viewing the Excel file Click Here Approach: Import required module.Import data from Excel
3 min read
How to Extract Text from Images with Python?
OCR (Optical Character Recognition) is the process of electronical conversion of Digital images into machine-encoded text. Where the digital image is generally an image that contains regions that resemble characters of a language. OCR is a field of research in pattern recognition, artificial intelligence and computer vision. This is due to the fact
4 min read
Extract speech text from video in Python
Nowadays, videos have become an integral part of our lives. Videos educate us and provide the necessary information. In this article, we will learn how to extract text speech from video using Python. Extract Speech Text from the Video To extract speech text from video in Python, we require the following modules to install, Here we are using Python
3 min read
Parsel: How to Extract Text From HTML in Python
Parsel is a Python library used for extracting data from HTML and XML documents. It provides tools for parsing, navigating, and extracting information using CSS selectors and XPath expressions. Parsel is particularly useful for web scraping tasks where you need to programmatically extract specific data from web pages. Key Features of ParselCSS Sele
2 min read
three90RightbarBannerImg