Skip to content

Instantly share code, notes, and snippets.

@mtik00
Created June 25, 2017 18:00
Show Gist options
  • Save mtik00/84c34297404d04aeab8dd332b11887f5 to your computer and use it in GitHub Desktop.
Save mtik00/84c34297404d04aeab8dd332b11887f5 to your computer and use it in GitHub Desktop.
Python script to convert a VCF file (address book) to a DYMO Address Book (ABX)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r'''
This script converts a vCard file to a Dymo ABX address book.
Usage:
vcf2abx <input VCF file> <output ABX file>
Example:
python vcf2abx.py %PROFILEDIR%\AddressBook\mybook.vcs \
"%USERPROFILE%\Documents\DYMO Label\Address Books\vcf2abx.ABX"
'''
# Imports #####################################################################
from __future__ import print_function
import sys
import xml.dom.minidom
import xml.etree.ElementTree as ET
import vobject
# Metadata ####################################################################
__author__ = 'Timothy McFadden'
__creationDate__ = '25-JUN-2017'
# Globals #####################################################################
def pf_xml(xml_data):
'''Return a 'pretty' formatted XML dom as a string.'''
parsed_xml = xml.dom.minidom.parseString(xml_data)
return parsed_xml.toprettyxml()
def main(infile, outfile): # pylint: disable=c0111
with open(infile) as filehandle:
vcf = filehandle.read()
address_book = ET.Element('AddressBook')
address_book.set('Version', '8.0')
address_book.set('DefaultPermutation', 'true')
address_book.set('Format', 'Native')
address_count = 0
for vcard in vobject.readComponents(vcf):
try:
vcard_name = str(vcard.contents['n'][0].value).strip().replace(
' ', ' ')
address_entry = ET.Element('AddressEntry')
address_data = ET.Element('AddressData')
address_data.text = "{name}\n{address}".format(
name=vcard_name,
address=str(vcard.contents['adr'][0].value).strip()
)
name = ET.Element('Name')
firstname = ET.Element('FirstName')
lastname = ET.Element('LastName')
fileas = ET.Element('FileAs')
firstname.text = vcard_name
fileas.text = firstname.text
name.extend([firstname, lastname, fileas])
address_entry.extend([address_data, name])
address_book.append(address_entry)
except Exception:
print("Error while converting:")
print(vcard)
raise
address_count += 1
stringified = pf_xml(ET.tostring(address_book))
with open(outfile, 'wb') as filehandle:
filehandle.write(stringified)
print('%i addresses converted' % address_count)
print('output stored as: %s' % outfile)
if __name__ == '__main__':
if len(sys.argv) != 3:
print('Usage: vcf2abx <input VCF file> <output ABX file>')
sys.exit(1)
main(infile=sys.argv[1], outfile=sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment