In this python file program, we will get all mobile numbers from a file with the help of the below-given steps.. Let’s consider we have readcontent.txt file with the below content.
Jay - 3569872214
Yash - 9865472589
Ketan - 8854632255
Rajesh - 7020589634
Steps to solve the program
- Open the first file by using open(“readcontent.txt”).
- Read the data and split it into words using file.read().split().
- Create an empty list to store the mobile number.
- Use a for loop to iterate over words.
- Check whether the word is a number or not using isnumeric().
- If yes then check whether the length of the number is 10 or not.
- If yes then add it to the empty list.
- Print the output.
# Open the file
file = open('readcontent.txt')
# Read data and converting it to words
data = file.read().split()
# Create an empty list
m_num = []
# Iterate over words
for val in data:
# Check whether a word in a numeric
if val.isnumeric():
# Check for mobile number
if len(val) == 10:
# Add number to the list
m_num.append(val)
# Print output
print("Mobile numbers in the file: ",m_num)
Output :
Mobile numbers in the file: [‘3569872214’, ‘9865472589’, ‘8854632255’, ‘7020589634’]
get all odd and even length words in two lists.