Python script to merge multiple vCard (.vcf) files into one.

#!/usr/bin/env python3
import os
import sys

# Check if the directory is provided as a command line argument
if len(sys.argv) != 2:
    print("Usage: python <directory>")

# Get the directory from the command line argument
directory = sys.argv[1]

# Check if the provided argument is a valid directory
if not os.path.isdir(directory):
    print(f"{directory} is not a valid directory.")

# Set the output file name to the directory name plus ".vcf"
output_file = os.path.basename(os.path.normpath(directory)) + '.vcf'
output_file_path = output_file

# Check if the output file already exists
if os.path.exists(output_file_path):
    print(f"{output_file_path} already exists. Exiting...")
    # Get a list of all .vcf files in the specified directory
    vcf_files = [file for file in os.listdir(directory) if file.endswith('.vcf') and file != output_file]

    # Open the output file in write mode
    with open(output_file_path, 'w', encoding="utf-8") as outfile:
        # Loop through each vcf file and append its contents to the output file
        for vcf in vcf_files:
            with open(os.path.join(directory, vcf), 'r', encoding="utf-8") as infile:
                    # Ensure there's a new line between different vCard files
                except UnicodeEncodeError:
                    print("Encode error while processing", vcf)

    print(f"All vCard files have been merged into {output_file_path}")