Fixing your adressbook using python

Our phones contain lots of contacts created before we realised omitting the country code was not an option. Fixing all of these by hand would be punishing. Luckily Google’s libphonenumber can handle that task quite well.

Using python this comes down to an extremely compact piece of code, using vobject and David Drysdale’s python port of libphonenumber. Before you use it though, make sure to set your home country in line 14.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import phonenumbers
import vobject

f = open('input.vcf', 'r')
for contact in vobject.readComponents(f):
    if hasattr(contact, 'tel'):
        #print(contact.fn.value.encode('utf-8'))
        for tel in contact.contents['tel']:
            oldnumber = tel.value
            number = phonenumbers.parse(oldnumber,"DE")
            newnumber = phonenumbers.format_number(number,
                        phonenumbers.PhoneNumberFormat.E164)
            tel.value = newnumber
    print(contact.serialize())
sys.exit(0)

The script reads contacts from a vCard-file called “input.vcf” (make sure it is placed in your working directory). It outputs the processed contacts to stdout. Typically you would use it like this:

$ python fixvcf.py > output.vcf

This post was inspired by a discussion on MobileMacs. There also exists a more full-featured app for OS X by Karsten Bruns.

Related Posts