Python Program to Extract Numbers from Text File

Text files often contain a mix of characters, numbers, and symbols. This program demonstrates how to create a Python program that reads a text file, extracts and identifies numbers within the text, and presents them to the user.

Problem Statement

Write a Python program that takes the name of a text file as input, reads the contents of the file, and extracts and displays all the numbers found in the text.

Python Program to Extract Numbers from Text File

import re
def extract_numbers_from_file(filename):
    try:
        with open(filename, 'r') as file:
            contents = file.read()
            numbers = re.findall(r'\d+', contents)
            return numbers
    except FileNotFoundError:
        return []

# Input
file_name = "sample.txt"  # Provide the name of your text file here

# Extracting numbers from file
number_list = extract_numbers_from_file(file_name)

# Output
if number_list:
    print("Numbers extracted from the file:", ', '.join(number_list))
else:
    print("No numbers found in the file.")

Input / Output

Python Program to Extract Numbers from Text File

Leave A Reply

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

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...