Python Practice › File Handling Programs › Program 5
Extract emails from a file
Write a Python program to get all email addresses from a text file.
Output
['asha@sqatools.in', 'ravi.k@gmail.com']
Approach
- Read the file and search it with a regular expression.
Solution
import re with open("contacts.txt", "w") as f: f.write("Asha asha@sqatools.in\nRavi ravi.k@gmail.com, phone 98765\nno email here\n") with open("contacts.txt") as f: text = f.read()print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))Output
['asha@sqatools.in', 'ravi.k@gmail.com']
Learn the concept
New to this topic? Read the lesson, then come back.