Created
March 22, 2024 14:44
-
-
Save 18520339/73dac6b9c136bc66ecd8e600296ad1e7 to your computer and use it in GitHub Desktop.
Export iCloud vCard contacts to csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import vobject | |
def vcard_to_csv(vcard_filename, csv_filename): | |
with open(vcard_filename, 'r', encoding='utf-8') as vcard_file: | |
vcards = vobject.readComponents(vcard_file.read()) | |
with open(csv_filename, mode='w', newline='', encoding='utf-8') as csv_file: | |
fieldnames = ['Name', 'Phone(s)', 'Email(s)', 'Address(es)'] | |
writer = csv.DictWriter(csv_file, fieldnames=fieldnames) | |
writer.writeheader() | |
for vcard in vcards: | |
contact = {} | |
contact['Name'] = vcard.fn.value | |
# Handling multiple phone numbers | |
phone_numbers = vcard.contents.get('tel', []) | |
contact['Phone(s)'] = '; '.join([phone.value for phone in phone_numbers]) | |
# Handling multiple email addresses | |
emails = vcard.contents.get('email', []) | |
contact['Email(s)'] = '; '.join([email.value for email in emails]) | |
# Handling multiple addresses | |
addresses = vcard.contents.get('adr', []) | |
formatted_addresses = [] | |
for address in addresses: | |
formatted_address = ' '.join(filter(None, [ | |
address.value.box, | |
address.value.street, | |
address.value.city, | |
address.value.region, | |
address.value.code, | |
address.value.country | |
])) | |
formatted_addresses.append(formatted_address) | |
contact['Address(es)'] = '; '.join(formatted_addresses) | |
writer.writerow(contact) | |
# Example usage | |
vcard_filename = 'iCloud vCards.vcf' | |
csv_filename = 'contacts.csv' | |
vcard_to_csv(vcard_filename, csv_filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment