Tag Archives: python

Splitting multiple-vCards-file to one-vCard-per-file

vCard is a standard format, defined for electronic business cards. vCards contain name, phone numbers, address, email address, URLs, photograph etc. These are stored as plain-text files of extension vcf or vcard.

Usually, one vCard file contains details of a single contact. But there are variations in its implementation. A few applications support multiple contacts in a single vCard file. GMail, Mac OS X and KDE Kontact are such applications. Microsoft Outlook and Symbian on the other hand allows only one contact per file. If you try to import a vCard file, with multiple contacts, they will import only the first contact.

I needed to convert single file containing multiple contacts to one-contact-per-file. For the same, I wrote a Python script. This script splits a vCard file to multiple files containing one contact each. This will help moving contacts to the applications which don’t support multiple contacts per file.

Example of vCard format

BEGIN:VCARD
VERSION:3.0
FN:Manjeet Dahiya
N:Dahiya;Manjeet;;;
EMAIL;TYPE=INTERNET:xxx@gmail.com
TEL;TYPE=CELL:xxx
END:VCARD

BEGIN:VCARD
VERSION:3.0
FN:Manjeet Dahiya
N:Dahiya;Manjeet;;;
EMAIL;TYPE=INTERNET:xxx@gmail.com
TEL;TYPE=CELL:xxx
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:Shivraj Singh
N:Singh;Shivraj;;;
EMAIL;TYPE=INTERNET:xxx@gmail.com
TEL;TYPE=CELL:xxx
END:VCARD

Script Usage

python vCardSplit <vcard-file>
import sys

if (len(sys.argv) != 2):
 print "Usage: vCardSplit <vcard file>\n"
 sys.exit()

vCardFilePath = sys.argv[1]

vCardFile = open(vCardFilePath, 'r')

a = 0
vcardStarted = False
while True:
 line = vCardFile.readline()
 if not line:
 break

 if line.startswith('BEGIN:VCARD'):
 vcardStarted = True
 a = a + 1
 splitFile = open('contact_' + str(a) + '.vcf', 'w')

 if vcardStarted:
 splitFile.write(line)

 if line.startswith('END:VCARD'):
 vcardStarted = False
 splitFile.close()

vCardFile.close()

print 'Generated ' + str(a) + ' vCards';