def test_basic_conversion(self): csv_content = """Name,Phone,Email John Doe,+1234567890,john@test.com"""
def detect_delimiter(self, sample: str) -> str: """Detect CSV delimiter (comma, semicolon, or tab)""" common_delimiters = [',', ';', '\t', '|'] delimiter_counts = {} for delimiter in common_delimiters: if delimiter in sample: # Count occurrences in first line first_line = sample.split('\n')[0] delimiter_counts[delimiter] = first_line.count(delimiter) if delimiter_counts: return max(delimiter_counts, key=delimiter_counts.get) return ',' # Default to comma
This complete feature provides a robust, production-ready CSV to VCF converter with extensive error handling, format detection, and customization options. csv to vcf
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'
class CSVToVCFConverter: """Convert CSV contacts to VCF vCard format""" row: Dict) ->
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)')
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 test_basic_conversion(self): csv_content = """Name
def normalize_contact(self, row: Dict) -> Dict: """Normalize contact data""" contact = {} for key, value in row.items(): if value and isinstance(value, str): value = value.strip() if value: contact[key] = value return contact