def extract_emails_from_file(filename): try: with open(filename, 'r') as file: text = file.read() pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]2,\b' emails = re.findall(pattern, text) return emails except FileNotFoundError: print(f"File 'filename' not found.") return []
# Example usage filename = 'example.txt' emails = extract_emails_from_file(filename) print("Extracted Emails:") for email in emails: print(email) Email List Txt
# Optionally, save emails to a new text file with open('email_list.txt', 'w') as f: for email in emails: f.write("%s\n" % email) print("Emails saved to email_list.txt") You can use grep to extract lines containing email addresses from a text file. \b' emails = re.findall(pattern