如何使用 Python 将类似 Mailchimp 的订阅者 CSV 转换为 vCard

如果你有一个带有如下表头的 CSV

csv_header_example.txt
"Email Address","First Name","Last Name",MEMBER_RATING,OPTIN_TIME,OPTIN_IP,CONFIRM_TIME,CONFIRM_IP,LATITUDE,LONGITUDE,GMTOFF,DSTOFF,TIMEZONE,CC,REGION,LAST_CHANGED,LEID,EUID,NOTES

你可以使用以下 Python 脚本将其转换为 vcard 文件目录:

csv_to_vcard.py
#!/usr/bin/env python3
import csv
import os
import argparse

# 设置参数解析器
parser = argparse.ArgumentParser(description='Convert a CSV file of contacts to vCard files.')
parser.add_argument('csv_file', type=str, help='Path to the CSV file containing contacts')

args = parser.parse_args()

# 从命令行参数定义 CSV 文件的路径
csv_file_path = args.csv_file

# 创建目录以存储 vCard 文件
vcard_directory = 'vcards'
os.makedirs(vcard_directory, exist_ok=True)

# 读取 CSV 文件并处理每个联系人
with open(csv_file_path, mode='r', encoding='utf-8') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    for row in csv_reader:
        # 提取联系人详情
        email = row['Email Address']
        first_name = row['First Name']
        last_name = row['Last Name']
        latitude = row['LATITUDE']
        longitude = row['LONGITUDE']
        notes = row['NOTES']

        # 创建 vCard 内容
        vcard_content = (
            f"BEGIN:VCARD\n"
            f"VERSION:3.0\n"
            f"N:{last_name};{first_name};;;\n"
            f"FN:{first_name} {last_name}\n"
            f"EMAIL;TYPE=INTERNET:{email}\n"
        )

        if latitude and longitude:
            vcard_content += f"GEO:{latitude};{longitude}\n"

        if notes:
            vcard_content += f"NOTE:{notes}\n"

        vcard_content += "END:VCARD\n"

        # 定义 vCard 的文件名
        vcard_file_name = f"{first_name}_{last_name}.vcf".replace(" ", "_")
        vcard_file_path = os.path.join(vcard_directory, vcard_file_name)

        # 将 vCard 内容写入文件
        with open(vcard_file_path, mode='w', encoding='utf-8') as vcard_file:
            vcard_file.write(vcard_content)

print(f"vCard 文件已创建在 '{vcard_directory}' 目录中。")

按类别查看类似文章: Python