Mobile numbers from a file

EasyFile Handling Programs · 18 of 38

Write a Python program to get all 10-digit mobile numbers from a file.

Advertisement
Output
['9876543210', '9123456780']

Approach

  1. re.findall(r"\b\d{10}\b", text).

Solution

Python
import re with open("contacts.txt", "w") as f:    f.write("Asha 9876543210\nRavi 12345\nMeena 9123456780 and 99887766554\n") with open("contacts.txt") as f:    print(re.findall(r"\b\d{10}\b", f.read()))
Output
['9876543210', '9123456780']

Line by line

Line 7

The 11-digit number does not match because \b requires the digits to end there.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs