How to Print All Numbers in a File with Python


In this example, we will learn how to print all the numbers presenting in a given text file by Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter the name of the file with .txt extension: ")
with open(fileName, 'r') as file:
    contentStr = " ".join(file.readlines())
    for i in contentStr:
        if i.isdigit():
            print(i)
Content of test3.txt: 
Python7 is an easy to learn5
powerful8 programming language25

Output:

Enter the name of the file with .txt extension: test3.txt
7
5
8
2
5
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement