Extract emails from a file

EasyFile Handling Programs · 5 of 38

Write a Python program to get all email addresses from a text file.

Advertisement
Output
['asha@sqatools.in', 'ravi.k@gmail.com']

Approach

  1. Read the file and search it with a regular expression.

Solution

Python
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.

More file handling programs

← All 38 File Handling Programs

Leave a Comment