How to Extract Numbers from 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 given text file. This tutorial will guide you step by step through the process of extracting all numbers within the 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. while True:
  2.     print("\n============= Extract Numbers from Text File =============\n")
  3.  
  4.     fname = input("Enter file name: ")
  5.  
  6.     try:
  7.         with open(fname, 'r') as f:
  8.             print("\nNumbers found in the file:")
  9.             for line in f:
  10.                 words = line.split()
  11.                 for word in words:
  12.                     number = ''.join([ch for ch in word if ch.isdigit()])
  13.                     if number:
  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 program extracts all numeric sequences from a text file. The user is prompted to enter the filename, and the program reads the file line by line. For each word in a line, it checks each character and collects only the digits to form numbers. All numbers found are displayed individually. If the file is not found, the program shows an error message. Users can repeatedly run the extraction process or exit the program gracefully.

Output:

There you have it we successfully created How to Extract Numbers from 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