Last modified: Nov 09, 2023 By Alexander Williams

Python: Extract Phone Numbers from a Text File

Extract Phone Numbers from a Text File Using Python


import re

# Define the path to the text file
file_path = "phone_numbers.txt"

# Regular expression pattern for matching phone numbers
phone_number_pattern = re.compile(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b')

# Initialize an empty list to store found phone numbers
found_phone_numbers = []

# Read the text file and search for phone numbers
with open(file_path, 'r') as file:
    for line in file:
        matches = phone_number_pattern.findall(line)
        found_phone_numbers.extend(matches)

# Check if any phone numbers were found and print them
if found_phone_numbers:
    for number in found_phone_numbers:
        print(f"Found phone number: {number}")
else:
    print("No phone numbers found.")

Output:


Found phone number: 123-456-7890
Found phone number: 456.789.0123
Found phone number: 789-012-3456