This is a Python Program to read a text file and print all numbers present in the text file.
The program takes the name of a file from the user and prints all the numbers present in the text file.
1. Take the file name from the user.
2. Read each line from the file and split the line to form a list of words.
3. Use a for loop to traverse through the words in the list and another for loop to traverse through the letters in the word.
3. Check if the letter provided by the user is a digit and if it is, print it.
4. Exit.
Here is source code of the Python Program to print all the numbers present in a text file. The program output is also shown below.
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)
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.
Case 1: Contents of file: hello world hello5 hello6 Output: Enter file name: out.txt 5 6 Case 2: Contents of file: hello world7 test2 test test8 Output: Enter file name: out1.txt 7 2 8
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Practice Programming MCQs
- Apply for Python Internship
- Apply for Programming Internship
- Check Information Technology Books
- Check Python Books