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.

# -*- coding: utf-8 -*-

import sys
import phonenumbers
import vobject

f = open('input.vcf', 'r')
for contact in vobject.readComponents(f):
    if hasattr(contact, 'tel'):
        for tel in contact.contents['tel']:
            oldnumber = tel.value
            number = phonenumbers.parse(oldnumber,"DE")
            newnumber = phonenumbers.format_number(number,
            tel.value = newnumber

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 > 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