|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import re |
| 3 | +import csv |
| 4 | +def contains_domain(address, domain): |
| 5 | + """Returns True if the email address contains the given,domain,in the domain position, false if not.""" |
| 6 | + domain = r'[\w\.-]+@'+domain+'$' |
| 7 | + if re.match(domain,address): |
| 8 | + return True |
| 9 | + return False |
| 10 | +def replace_domain(address, old_domain, new_domain): |
| 11 | + """Replaces the old domain with the new domain in the received address.""" |
| 12 | + old_domain_pattern = r'' + old_domain + '$' |
| 13 | + address = re.sub(old_domain_pattern, new_domain, address) |
| 14 | + return address |
| 15 | +def main(): |
| 16 | + """Processes the list of emails, replacing any instances of the old domain with the new domain.""" |
| 17 | + old_domain, new_domain = 'abc.edu', 'xyz.edu' |
| 18 | + csv_file_location = '/home/<username>/data/user_emails.csv' |
| 19 | + report_file = '<path_to_home_directory>' + '/updated_user_emails.csv' |
| 20 | + user_email_list = [] |
| 21 | + old_domain_email_list = [] |
| 22 | + new_domain_email_list = [] |
| 23 | + with open(csv_file_location, 'r') as f: |
| 24 | + user_data_list = list(csv.reader(f)) |
| 25 | + user_email_list = [data[1].strip() for data in user_data_list[1:]] |
| 26 | + for email_address in user_email_list: |
| 27 | + if contains_domain(email_address, old_domain): |
| 28 | + old_domain_email_list.append(email_address) |
| 29 | + replaced_email = replace_domain(email_address,old_domain,new_domain) |
| 30 | + new_domain_email_list.append(replaced_email) |
| 31 | + email_key = ' ' + 'Email Address' |
| 32 | + email_index = user_data_list[0].index(email_key) |
| 33 | + for user in user_data_list[1:]: |
| 34 | + for old_domain, new_domain in zip(old_domain_email_list, new_domain_email_list): |
| 35 | + if user[email_index] == ' ' + old_domain: |
| 36 | + user[email_index] = ' ' + new_domain |
| 37 | + f.close() |
| 38 | + with open(report_file, 'w+') as output_file: |
| 39 | + writer = csv.writer(output_file) |
| 40 | + writer.writerows(user_data_list) |
| 41 | + output_file.close() |
| 42 | + |
| 43 | +main() |
| 44 | + |
0 commit comments