I am working on some vcard files in python. I have parsed vcard file into a dictionary. Now I want to save it to a new vcf file after editing it. I couldn't find any solution to this. Is there any library or module which parse python dictionary in vcards ?
person = {'n': 'Forrest Gump',
'fn': 'Forrest Gump', 'tel': '(111) 555-1212',
'email': '[email protected]',
'photo': ';http://www.example.com/dir_photos/my_photo.gif',
'adr': 'Kathmandu, Nepal'}
I want to get a vcf file like the following when I give this dictionary.
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.;
FN:Forrest Gump
TITLE:Shrimp Man
PHOTO;VALUE=URI;TYPE=GIF:;http://www.example.com/dir_photos/my_photo.gif
EMAIL:[email protected]
END:VCARD
You should probably take a look at vobject here http://eventable.github.io/vobject/
import vobject
person = {'n': 'Forrest Gump',
'fn': 'Forrest Gump', 'tel': '(111) 555-1212',
'email': '[email protected]',
'photo': ';http://www.example.com/dir_photos/my_photo.gif',
'adr': 'Kathmandu, Nepal'}
vcard = vobject.readOne('\n'.join([f'{k}:{v}' for k, v in person.items()]))
vcard.name = 'VCARD'
vcard.useBegin = True
vcard.prettyPrint()
with open('test.vcf', 'w', newline='') as f:
f.write(vcard.serialize())
Note that writing the card without .name and .useBegin set will omit the BEGIN and END and the resulting file will not be a valid vCard. I'm not sure if there's a more convenient way to do this using this library, but you could simply create your own class that inherits from the existing one (or call the function from a new one) to clean up the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With