Created
June 27, 2024 18:44
-
-
Save themorgantown/6e9779dc2258fc84cc0a4bd09ba1ce4c to your computer and use it in GitHub Desktop.
keeps name, tel, email, and address.
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 vobject | |
import logging | |
from tqdm import tqdm | |
def minimize_vcf(input_file, output_file, fields_to_keep=None): | |
if fields_to_keep is None: | |
fields_to_keep = ['n', 'fn', 'tel', 'email', 'adr'] | |
fields_to_keep = [field.lower() for field in fields_to_keep] | |
logging.info(f"Processing file: {input_file}") | |
logging.info(f"Fields to keep: {fields_to_keep}") | |
try: | |
with open(input_file, 'r', encoding='utf-8') as f: | |
vcards = list(vobject.readComponents(f, ignoreUnreadable=True)) | |
total_cards = len(vcards) | |
logging.info(f"Total contacts found: {total_cards}") | |
with open(output_file, 'w', encoding='utf-8') as f: | |
for vcard in tqdm(vcards, desc="Processing contacts"): | |
# Check if FN exists, if not, create one | |
if 'fn' not in vcard.contents: | |
if 'n' in vcard.contents: | |
n = vcard.n.value | |
fn = f"{n.given} {n.family}".strip() | |
vcard.add('fn').value = fn | |
else: | |
vcard.add('fn').value = "Unknown" | |
logging.warning(f"Created missing FN field for contact: {vcard.fn.value}") | |
# Keep only specified fields | |
for field in list(vcard.contents): | |
if field.lower() not in fields_to_keep: | |
del vcard.contents[field] | |
f.write(vcard.serialize()) | |
logging.info(f"Minimized VCF saved to: {output_file}") | |
except IOError as e: | |
logging.error(f"IO Error: {e}") | |
except Exception as e: | |
logging.error(f"Unexpected error: {e}") | |
if __name__ == "__main__": | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
input_file = 'input.vcf' | |
output_file = 'output_minimized.vcf' | |
fields_to_keep = ['n', 'fn', 'tel', 'email', 'adr'] | |
minimize_vcf(input_file, output_file, fields_to_keep) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment