Skip to content

Instantly share code, notes, and snippets.

@merqurio
Created June 24, 2014 00:40
Show Gist options
  • Save merqurio/e10519375a8dcaa6b3cb to your computer and use it in GitHub Desktop.
Save merqurio/e10519375a8dcaa6b3cb to your computer and use it in GitHub Desktop.
Get all the emails in a text and export it to a CSV file
import os
import re
import csv
# Import the file
MYPATH = os.path.dirname(os.path.abspath(__file__))
FILENAME = input('The filename is : ')
INPUT_FILE = os.path.join(MYPATH, FILENAME)
def check_file(input_file):
'''Check if file exists and creates an Object'''
if os.path.exists(input_file):
data = open(input_file, 'r')
return data.read()
else:
print("File not found.")
raise SystemExit
def read_file(data_read):
'''Read & returns Emails'''
r = re.compile(("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"
"{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"
"\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))
# Reads texts and returns emails
return r.findall(data_read)
def write_csv(emails):
'''Write a CSV file with the emails'''
# Define CSV
new_filename = FILENAME[:-4]+".csv"
# Create file
with open(os.path.join(MYPATH, new_filename), "w") as myFile:
writer = csv.writer(myFile)
for email in emails:
writer.writerow(email)
print("Done !")
write_csv(read_file(check_file(INPUT_FILE)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment