Skip to content

Commit 80269e0

Browse files
authored
Script replaces given domain to another from a csv
Draft (but working) script that replaces given domain to another, data exctracted from a csv
1 parent afae07e commit 80269e0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

replacedomain.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)