-
Notifications
You must be signed in to change notification settings - Fork 14
/
vcard2csv.py
executable file
·161 lines (148 loc) · 5.09 KB
/
vcard2csv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python
import vobject
import glob
import csv
import argparse
import os.path
import sys
import logging
import collections
column_order = [
'Name',
'Full name',
'Cell phone',
'Work phone',
'Home phone',
'Email',
'Note',
]
def get_phone_numbers(vCard):
cell = home = work = None
for tel in vCard.tel_list:
if vCard.version.value == '2.1':
if 'CELL' in tel.singletonparams:
cell = str(tel.value).strip()
elif 'WORK' in tel.singletonparams:
work = str(tel.value).strip()
elif 'HOME' in tel.singletonparams:
home = str(tel.value).strip()
else:
logging.warning("Warning: Unrecognized phone number category in `{}'".format(vCard))
tel.prettyPrint()
elif vCard.version.value == '3.0':
if 'CELL' in tel.params['TYPE']:
cell = str(tel.value).strip()
elif 'WORK' in tel.params['TYPE']:
work = str(tel.value).strip()
elif 'HOME' in tel.params['TYPE']:
home = str(tel.value).strip()
else:
logging.warning("Unrecognized phone number category in `{}'".format(vCard))
tel.prettyPrint()
else:
raise NotImplementedError("Version not implemented: {}".format(vCard.version.value))
return cell, home, work
def get_info_list(vCard, vcard_filepath):
vcard = collections.OrderedDict()
for column in column_order:
vcard[column] = None
name = cell = work = home = email = note = None
vCard.validate()
for key, val in list(vCard.contents.items()):
if key == 'fn':
vcard['Full name'] = vCard.fn.value
elif key == 'n':
name = str(vCard.n.valueRepr()).replace(' ', ' ').strip()
vcard['Name'] = name
elif key == 'tel':
cell, home, work = get_phone_numbers(vCard)
vcard['Cell phone'] = cell
vcard['Home phone'] = home
vcard['Work phone'] = work
elif key == 'email':
email = str(vCard.email.value).strip()
vcard['Email'] = email
elif key == 'note':
note = str(vCard.note.value)
vcard['Note'] = note
else:
# An unused key, like `adr`, `title`, `url`, etc.
pass
if name is None:
logging.warning("no name for vCard in file `{}'".format(vcard_filepath))
if all(telephone_number is None for telephone_number in [cell, work, home]):
logging.warning("no telephone numbers for file `{}' with name `{}'".format(vcard_filepath, name))
return vcard
def get_vcards(vcard_filepath):
with open(vcard_filepath) as fp:
all_text = fp.read()
for vCard in vobject.readComponents(all_text):
yield vCard
def readable_directory(path):
if not os.path.isdir(path):
raise argparse.ArgumentTypeError(
'not an existing directory: {}'.format(path))
if not os.access(path, os.R_OK):
raise argparse.ArgumentTypeError(
'not a readable directory: {}'.format(path))
return path
def writable_file(path):
if os.path.exists(path):
if not os.access(path, os.W_OK):
raise argparse.ArgumentTypeError(
'not a writable file: {}'.format(path))
else:
# If the file doesn't already exist,
# the most direct way to tell if it's writable
# is to try writing to it.
with open(path, 'w') as fp:
pass
return path
def main():
parser = argparse.ArgumentParser(
description='Convert a bunch of vCard (.vcf) files to a single TSV file.'
)
parser.add_argument(
'read_dir',
type=readable_directory,
help='Directory to read vCard files from.'
)
parser.add_argument(
'tsv_file',
type=writable_file,
help='Output file',
)
parser.add_argument(
'-v',
'--verbose',
help='More verbose logging',
dest="loglevel",
default=logging.WARNING,
action="store_const",
const=logging.INFO,
)
parser.add_argument(
'-d',
'--debug',
help='Enable debugging logs',
action="store_const",
dest="loglevel",
const=logging.DEBUG,
)
args = parser.parse_args()
logging.basicConfig(level=args.loglevel)
vcard_pattern = os.path.join(args.read_dir, "*.vcf")
vcard_paths = sorted(glob.glob(vcard_pattern))
if len(vcard_paths) == 0:
logging.error("no files ending with `.vcf` in directory `{}'".format(args.read_dir))
sys.exit(2)
# Tab separated values are less annoying than comma-separated values.
with open(args.tsv_file, 'w', encoding="utf-8", newline='') as tsv_fp:
writer = csv.writer(tsv_fp, delimiter='\t')
writer.writerow(column_order)
for vcard_path in vcard_paths:
for vcard in get_vcards(vcard_path):
vcard_info = get_info_list(vcard, vcard_path)
writer.writerow(list(vcard_info.values()))
if __name__ == "__main__":
main()