def test_basic_conversion(self): csv_content = """Name,Phone,Email John Doe,+1234567890,john@test.com"""
parser.add_argument('input', help='Input CSV file path') parser.add_argument('-o', '--output', help='Output VCF file path') parser.add_argument('-e', '--encoding', help='CSV file encoding (auto-detected if not specified)')
class CSVToVCFConverter: """Convert CSV contacts to VCF vCard format"""
def format_date(self, date_str: str) -> str: """Format date for VCF (YYYYMMDD)""" if not date_str: return "" # Try different date formats formats = ['%Y-%m-%d', '%m/%d/%Y', '%d/%m/%Y', '%Y%m%d'] for fmt in formats: try: date_obj = datetime.strptime(date_str, fmt) return date_obj.strftime('%Y%m%d') except ValueError: continue return date_str.replace('-', '').replace('/', '')
def __init__(self): self.version = "3.0" self.encoding_detected = False def detect_encoding(self, file_path: str) -> str: """Detect file encoding automatically""" with open(file_path, 'rb') as f: raw_data = f.read() result = chardet.detect(raw_data) return result['encoding'] or 'utf-8'
try: count = converter.convert(args.input, args.output, args.encoding) print(f"\n✓ Conversion complete! count contacts converted.") return 0 except Exception as e: print(f"\n✗ Error: str(e)") return 1 if == " main ": exit(main()) 3. Installation Requirements # Install required package pip install chardet Or create requirements.txt echo "chardet>=5.0.0" > requirements.txt pip install -r requirements.txt 4. Usage Examples # Basic conversion python csv_to_vcf.py contacts.csv Specify output file python csv_to_vcf.py contacts.csv -o my_contacts.vcf Specify encoding for non-UTF8 files python csv_to_vcf.py contacts.csv -e iso-8859-1 In Python script from csv_to_vcf import CSVToVCFConverter
def convert(self, input_file: str, output_file: Optional[str] = None, encoding: Optional[str] = None) -> int: """Convert CSV to VCF and save to file""" # Read CSV contacts = self.read_csv(input_file, encoding) if not contacts: print("No valid contacts found in CSV file") return 0 print(f"Found len(contacts) contacts") # Determine output filename if not output_file: input_path = Path(input_file) output_file = input_path.stem + '.vcf' # Write VCF file try: with open(output_file, 'w', encoding='utf-8') as f: for i, contact in enumerate(contacts, start=1): vcf_card = self.create_vcf_card(contact, i) f.write(vcf_card) if i < len(contacts): f.write('\n') print(f"Successfully converted len(contacts) contacts to output_file") return len(contacts) except Exception as e: raise Exception(f"Error writing VCF file: str(e)")