Skip to content

Instantly share code, notes, and snippets.

@davidandrzej
Created September 24, 2011 20:16
Show Gist options
  • Save davidandrzej/1239809 to your computer and use it in GitHub Desktop.
Save davidandrzej/1239809 to your computer and use it in GitHub Desktop.
Script to help semi-automatically tidy up Google contacts
"""
Python script to help programmatically tidy up Google contacts
Example workflow:
1) export Google contacts and back this file up somewhere
(must use Outlook CSV format b/c Python csv chokes on Unicode)
2) run this script to generate a cleaned-up CSV contacts file
3) in Google contacts, delete all and re-import from this new CSV
4) use Google contacts merge/delete for finishing touches
"""
import csv
import sys
phonefields = ['Primary Phone', 'Home Phone', 'Home Phone 2',
'Mobile Phone', 'Company Main Phone', 'Business Phone',
'Business Phone 2', "Assistant's Phone",
'Other Phone', 'Car Phone', 'Radio Phone', 'TTY/TDD Phone']
emailfields = ['E-mail Address', 'E-mail 2 Address', 'E-mail 3 Address']
def hasField(person, fields):
""" Does person have an entry for any of these fields? """
return any([len(person[f]) > 0 for f in fields])
def removeNone(person):
""" Need to make sure there are no 'none' keys before writing out """
if None in person.keys():
del person[None]
return person
def quickprint(person):
""" Print out what info we do have for this person """
return '\n'.join(['%s: %s' % (key, val) for (key,val)
in person.items()
if len(val) > 0])
# Read in the contact list
contacts = csv.DictReader(open('contacts.csv','rb'))
# Discard contacts for which we have no e-mail or phone
havecontact = [removeNone(person) for person in contacts
if hasField(person, phonefields) or
hasField(person, emailfields)]
# Interactively let user give thumbs up/down for remaining contacts
keepcontact = []
for hc in havecontact:
print '\n'
print quickprint(hc)
print 'Keep (y/n)?'
if('y' in sys.stdin.readline().lower()):
keepcontact.append(hc)
print 'KEEP OK\n'
# Write out contacts to keep (along with field names header)
outf = open('keep-contacts.csv','w')
outf.write(','.join(contacts.fieldnames) + '\n')
writer = csv.DictWriter(outf, contacts.fieldnames)
writer.writerows(keepcontact)
outf.close()
@Yeikop
Copy link

Yeikop commented Apr 4, 2021

Hello,

I am finding a Script where I can add CSV file contacts to different users, Your Script is valid?

I have a lot CSV Files of different Users and I would like to add by Script this CSV files into the Google Accounts by Api contacts or Python Script, if you can help me I will appreciate it.

Many thanks

@davidandrzej
Copy link
Author

davidandrzej commented Apr 5, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment