Skip to content

Instantly share code, notes, and snippets.

@senko
Created May 14, 2012 07:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save senko/2692527 to your computer and use it in GitHub Desktop.
Save senko/2692527 to your computer and use it in GitHub Desktop.
Simple vCard to CSV converter (only uses name, phone, email info)
#!/usr/bin/env python
"""
Parse phone and email records out of vCard file and store them in a CSV.
Copyright (C) 2012 Senko Rasic <senko.rasic@dobarkod.hr>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import csv
import sys
import logging
import vobject
log = logging.getLogger(__name__)
def sanitize_phone(num, country_prefix):
"""
Convert phone numbers into standard +<ccode><phonenum> format, without
spaces, dashes or slashes. The default country prefix used is +385
(Croatia).
"""
orig = num
num = num.replace(' ', '').replace('-', '').replace('/', '')
if num.startswith('0'):
if num.startswith('00'):
num = '+' + num[2:]
else:
num = '+' + country_prefix + num[1:]
elif not num.startswith('+') and len(num) > 5:
num = '+' + num
if num != orig:
log.debug('[sanitize_phone] %s -> %s' % (orig, num))
return num
def parse(fname, country_prefix):
"""
Parse vCard file. Returns a generator producing dicts with 'name' (string),
'emails' (list of strings) and 'phones' (list of strings) fields.
"""
for vobj in vobject.readComponents(open(fname)):
if not hasattr(vobj, 'fn'):
log.warning('[parse] skipping entry with no name: ' + repr(vobj))
continue
entry = {
'name': vobj.fn.value.strip(),
'emails': [],
'phones': []
}
if hasattr(vobj, 'email_list'):
entry['emails'] = [e.value.strip() for e in vobj.email_list]
if hasattr(vobj, 'tel_list'):
entry['phones'] = [sanitize_phone(t.value, country_prefix)
for t in vobj.tel_list]
log.debug('[parse] got entry for ' + entry['name'])
yield entry
def csv_output(fname, entries):
"""
Write the entries generated by parse() to a UTF-8 encoded CSV file with
three columns: Name, Phones and Emails.
"""
with open(fname, 'wb') as fd:
writer = csv.writer(fd)
writer.writerow(['Name', 'Phones', 'Emails'])
for e in entries:
writer.writerow([
e['name'].encode('utf-8'),
','.join(e['phones']),
','.join(e['emails'])
])
def vcf2csv(infile, outfile, country_prefix):
"""
Parse entries out of vCard 'infile' and store them to CSV 'outfile'.
"""
csv_output(outfile, parse(infile, country_prefix))
if __name__ == '__main__':
if len(sys.argv) != 3 and len(sys.argv) != 4:
print "Usage: %s <infile.vcf> <outfile.csv> [<prefix>]" % sys.argv[0]
print "Default country prefix: 385 (Croatia)"
sys.exit(-1)
logging.basicConfig(level=logging.INFO)
vcf2csv(sys.argv[1], sys.argv[2],
sys.argv[3] if len(sys.argv) == 4 else '385')
@blitzdesigner
Copy link

Hi,
I found your code looking for a way to import a vcf to a grandstream ip-phone, but unfortunately I get an error running your code:

Traceback (most recent call last):
File "vcf2csv.py", line 117, in
sys.argv[3] if len(sys.argv) == 4 else '49')
File "vcf2csv.py", line 107, in vcf2csv
csv_output(outfile, parse(infile, country_prefix))
File "vcf2csv.py", line 96, in csv_output
e['name'].encode('utf-8'),
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 11: ordinal not in range(128)

I found out that this has something to do with the handling of unicode resp. UTF8 encoding, But I dont know any python :-)

so, can you help me with this?

thanks a lot,
greetings blitzdesigner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment