Splitting VCF files using Python

I recently did a fresh install of Ubuntu 11.10. I forgot to export my contacts from Evolution and was horrified to learn these are not stored in a flat file and the database is not compatible between versions (great work Evolution devs).

Some poking around on the internet led me to a Perl file to that was able to get the data. Then some Python work let me format it correctly as a VCARD (.VCF) file. But when I tried to import it I didn’t get all my contacts. More sleuthing led me to realize that only the first 75 were being imported. I wrote this short Python script to break up my 190-contact VCARD file into parts that had no more than 75 entries. I hope it will help you out too!

#split vcf files

working_dir = '/home/mike/compile/'
input_file = 'final.vcf'
output_seed = 'contacts-part-'
vcards_per_file = 75

with open(working_dir + input_file,'r') as f:
    count = 0
    output_count = 1
    results = []
    for line in f:
        if ("BEGIN:VCARD" in line):
            count += 1
        if (count <= vcards_per_file):
            results.append(line)
        else:
            #output file with stored values
            with open(working_dir + output_seed + str(output_count) + '.vcf','w') as oFile:
                for item in results:
                    oFile.write(item)

            #increment outputfile count
            output_count += 1

            #clear results list and append last read line
            del results[:]
            results.append(line)

            #set counter back to 1
            count = 1
            

    #write the last set of results to a file
    with open(working_dir + output_seed + str(output_count) + '.vcf','w') as oFile:
        for item in results:
            oFile.write(item)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Before you submit form:
Human test by Not Captcha