Created
March 20, 2016 18:17
-
-
Save dniku/6262b184ca3a8c990d4a to your computer and use it in GitHub Desktop.
Converts a CSV with contacts exported from Google to a VCF (vCard) file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import vobject | |
def to_vcard(item): | |
item = item.map(lambda s: s.strip()) | |
c = vobject.vCard() | |
c.add('n') | |
if item['Additional Name']: | |
c.n.value = vobject.vcard.Name( | |
family=item['Family Name'], | |
given=item['Given Name'], | |
additional=item['Additional Name'] | |
) | |
else: | |
c.n.value = vobject.vcard.Name(family=item['Family Name'], given=item['Given Name']) | |
c.add('fn') | |
c.fn.value = item['Name'] | |
simple_pairs = [ | |
('Nickname', 'nickname'), | |
('Birthday', 'bday'), | |
('Notes', 'note') | |
] | |
for p1, p2 in simple_pairs: | |
if item[p1]: | |
c.add(p2) | |
getattr(c, p2).value = item[p1] | |
if item['Group Membership']: | |
c.add('categories') | |
c.categories.value = [g.lstrip('* ') for g in item['Group Membership'].split(' ::: ')] | |
for i in range(1, 4): | |
if item['E-mail %d - Value' % i]: | |
for elem in item['E-mail %d - Value' % i].split(' ::: '): | |
c.add('email') | |
c.contents['email'][-1].value = elem | |
c.contents['email'][-1].type_param = item['E-mail %d - Type' % i].lstrip('* ') | |
for i in range(1, 6): | |
if item['Phone %d - Value' % i]: | |
for elem in item['Phone %d - Value' % i].split(' ::: '): | |
c.add('tel') | |
c.contents['tel'][-1].value = elem | |
c.contents['tel'][-1].type_param = item['Phone %d - Type' % i].lstrip('* ') | |
# Doesn't work, no idea why | |
# for i in range(1, 2): | |
# if item['Website %d - Value' % i]: | |
# c.add('item1.URL') | |
# print(c.contents) | |
# c.contents['item1.URL'][i - 1].value = item['Website %d - Value' % i] | |
# c.add('item1.X-ABLabel') | |
# c.contents['item1.X-ABLabel'][i - 1].type_param = item['Website %d - Type' % i] | |
return c | |
def convert(src='google.csv', dst='contacts.vcf'): | |
df = pd.read_csv(src, encoding='utf-8') | |
df.fillna(u'', inplace=True) | |
with open(dst, 'w') as f: | |
for i, item in df.iterrows(): | |
f.write(to_vcard(item).serialize()) | |
if __name__ == '__main__': | |
convert() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment