Let’s say that you have a vCard file. You can export it from your Mac OS X AddressBook.app, or from any other similar application. Now you need to extract some information from it, namely the e-mails, for spamming your friends with some boring news. Typical.
Enter vobject. This Python library is part of the Chandler effort (which seems to be somewhat ill-fated since Mitch Kapor announced he was leaving the project). Anyway, you can download this library from here and then install it using the common sequence:
python setup.py build
python setup.py install
Finally, here’s a bit of code to quickly extract the names and e-mail addresses from a vCard file called “vCards.vcf” containing lots of vCard instances, one after the other (AddressBook.app exports data this way, instead of creating on file per contact):
The library documentation, to put it simply, isn’t as good as the library itself (see? I can be politically correct sometimes :) Maybe I missed a better way to iterate over the contents of the whole stream of vCard instances inside the file (using exceptions for that is yuck!), but then again, feel free to add your comments below as usual.
2 Comments
#1. Jeffrey Harris 04.26.2008
Hi,
Thanks for being diplomatic about the auto-generated library docs. You’re right, they’re not much use, I’m tempted to stop building them.
Really, it’s better to look at:
http://vobject.skyhouseconsulting.com/usage.html
readComponents is a Python iterator, so it’s true you can use an iterator’s next() method to iterate over it, but you’d be better off just iterating over vCards using a for loop, since Python understands iterators. Here’s a simpler way to write your example:
import vobject
f = open(”vCards.vcf”)
a = vobject.readComponents(f)
counter = 0
for b in a:
if ‘email’ in b.contents:
counter += 1
print repr(b.fn.value), repr(b.email.value)
f.close()
print “%d e-mails found.” % counter
#2. Adrian 04.26.2008
Hi Jeffrey! Thanks for your comments! Indeed it was hard to get that part, and it’s great that you point me that way. In any case the library is EXTREMELY useful to me and my project right now, so thanks!
Commenting