How to Extract Numbers from a Text File in Python

In this tutorial, we will learn how to program "How to Extract Numbers from a Text File in Python". The objective is to extract numbers from a text file. This tutorial will guide you step by step through methods for extracting numbers from any text file. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of extracting numbers from a text file. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. import re  # regular expressions
  2.  
  3. while True:
  4.     print("\n================== Extract Numbers from a Text File ==================\n")
  5.  
  6.     fname = input("Enter file name: ")
  7.  
  8.     try:
  9.         with open(fname, 'r') as f:
  10.             print("\nNumbers found in the file:")
  11.             for line in f:
  12.                 numbers = re.findall(r'\d+', line)  # find all numeric sequences
  13.                 for number in numbers:
  14.                     print(number)
  15.     except FileNotFoundError:
  16.         print(f"File '{fname}' not found!")
  17.  
  18.     # Ask user if they want to try again
  19.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  20.     if opt == 'no':
  21.         print("Exiting program...")
  22.         break
  23.     elif opt != 'yes':
  24.         print("Invalid choice. Exiting program...")
  25.         break

This Python program extracts all numbers from a text file. It prompts the user to enter the filename, reads the file line by line, and uses regular expressions to find all numeric sequences in each line. Each number found is printed to the console. The user can repeat the process with another file or exit the program.

Output:

There you have it we successfully created How to Extract Numbers from a Text File in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials