by BehindJava

Write a program to read a Text File and Print all the Numbers Present in the Text File in Python

Home » python » Write a program to read a Text File and Print all the Numbers Present in the Text File in Python

In this tutorial we are going to learn about reading a Text File and Print all the Numbers Present in the Text File in Python.

Python Program to Read a Text File and Print all the Numbers Present in the Text File

fname = input("Enter file name: ")
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        for i in words:
            for letter in i:
                if(letter.isdigit()):
                    print(letter)

Explanation

  1. User must enter a file name.
  2. The file is opened using the open() function in the read mode.
  3. A for loop is used to read through each line in the file.
  4. Each line is split into a list of words using split().
  5. A for loop is used to traverse through the words list and another for loop is used to traverse through the letters in the word.
  6. If the letter encountered is a digit, the digit is printed.