import
os
import
vobject
import
csv
def
work(inputFile, outputFile):
with
open
(inputFile,
'r'
, encoding
=
'gbk'
) as f:
contacts
=
f.read()
try
:
index
=
0
allKeys
=
[]
vcards
=
vobject.readComponents(contacts)
for
vcard
in
vcards:
index
+
=
1
keys
=
vcard.contents.keys()
for
key
in
keys:
if
key
not
in
allKeys:
allKeys.append(key)
print
(f
'allKeys:{allKeys}'
)
with
open
(outputFile,
'w'
, newline
=
'
', encoding='
gbk') as f:
writer
=
csv.writer(f)
writer.writerow(allKeys)
vcards
=
vobject.readComponents(contacts)
for
vcard
in
vcards:
row
=
[]
for
key
in
allKeys:
if
key
in
vcard.contents.keys():
content
=
vcard.contents[key]
tmp
=
''
for
item
in
content:
if
item.value
is
not
None
:
tmp
+
=
str
(item.value)
+
';'
row.append(tmp[:
-
1
])
else
:
row.append('')
print
(row)
writer.writerow(row)
except
Exception as e:
print
(
"An error occurred:"
, e)
if
'__main__'
=
=
__name__:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
inputFile
=
'contacts.vcf'
outputFile
=
'output.csv'
work(inputFile, outputFile)