File Content Reader with Email Extraction

  • Share this:

Code introduction


This function reads the content of a file at the specified path and returns the read content. If an encoding is specified, it will use that encoding to read the file.


Technology Stack : File operations, exception handling, encoding

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re

def read_file(file_path, mode='r', encoding='utf-8'):
    with open(file_path, mode, encoding=encoding) as file:
        return file.read()

def extract_emails(text):
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    return re.findall(email_pattern, text)