Skip to content

Commit 576435c

Browse files
committed
add a script to create a sql file to update emails from csv list
1 parent 843bb6c commit 576435c

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

examples/16-update-users-emails.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env python
2+
3+
###############
4+
# DESCRIPTION #
5+
##############
6+
#
7+
# This script will read a csv file that contains a list of emails to update,
8+
# with a column "old_email" that exist in the database, and a column
9+
# "new_email" with the value that we want to push to the database.
10+
# It will then generate a .sql file to update these values directly in the database.
11+
12+
# we will use the generic csv module
13+
import csv
14+
15+
CSV_PATH = './data/users-emails.csv'
16+
OUTPUT_PATH = './update-emails.sql'
17+
OLD_EMAIL_COLUMN = 'old_email'
18+
NEW_EMAIL_COLUMN = 'new_email'
19+
20+
with open(OUTPUT_PATH, 'w') as outfile:
21+
pass # This just to clear any previous content
22+
23+
# Note: use encoding='utf-8-sig' in the open() call if your file has BOM (Byte Order Mark)
24+
# Also make sure that the CSV file was saved as UTF-8 to avoid issues with special characters
25+
with open(CSV_PATH, newline='') as csvfile:
26+
# let's read the CSV using the standard "csv" library from python. No need for anything fancier.
27+
csvreader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
28+
with open(OUTPUT_PATH, 'a') as outfile:
29+
# now we loop over each row in our CSV
30+
for row in csvreader:
31+
line = f"UPDATE users SET email = '{row[NEW_EMAIL_COLUMN]}' WHERE email = '{row[OLD_EMAIL_COLUMN]}';\n"
32+
outfile.write(line)
33+
34+
print(f'SQL file written to {OUTPUT_PATH}')

examples/data/users-emails.csv

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
old_email,new_email,another column
2+
3+
4+
5+
[email protected],[email protected],This email doesn’t exist in the database

0 commit comments

Comments
 (0)