Python Script to Copy Picasa Rated Pictures to a Separate Folder

From Catholicpenguin


from __future__ import with_statement
import sys
import os
import os.path
import shutil

DBG = True

def parse_picasa_ini_file(picasa_file_name):
    '''Parses Picasa .picasa.ini file and returns a list of tuples, in the form
    (picture, {dict of properties}'''
    pictures = []

    with open(picasa_file_name, 'r') as f:
        picasa_data = f.read().split('\n')

    while len(picasa_data) != 0:
        filename = picasa_data.pop(0)[1:-1]
        properties = {}
        while len(picasa_data) != 0 and not picasa_data[0].startswith('['):
            prop = picasa_data.pop(0).strip()
            if prop == '': continue
            key,value = prop.split('=')
            properties[key]=value
            pictures.append((filename,properties))

    return pictures

if len(sys.argv) != 3:
    print 'Parses .picasa.ini file from a folder of pictures, and copies rated .JPG'
    print '  (and .NEF if exists) to a folder specified.'
    print 'Usage: script.py <Picasa .picasa.ini file> <Folder to copy rated to>'
else:
    picasa_file_name = os.path.abspath(sys.argv[1])
    orig_pics_folder = os.path.dirname(picasa_file_name)
    good_pics_folder = sys.argv[2]
    if DBG: print 'Parsing metadata from %s with a path of %s to folder %s' % \
       (picasa_file_name, orig_pics_folder, good_pics_folder)
    
    pictures = parse_picasa_ini_file(picasa_file_name)

    for picture, properties in pictures:
        fn_jpg_from = os.path.join(orig_pics_folder,picture)
        fn_jpg_to = os.path.join(good_pics_folder,picture)
        fn_nef_from = os.path.join(orig_pics_folder,picture[:-3]+'NEF')
        fn_nef_to = os.path.join(good_pics_folder,picture[:-3]+'NEF')
        
        if 'star' in properties and properties['star'] == 'yes':
            starred = True
        else:
            starred = False

        if starred:
            print 'Picture %s rated; copying' % (picture)
            if not os.path.exists(good_pics_folder):
                print "Dest folder %s doesn't exist; creating" % \
                   (good_pics_folder)
                os.makedirs(good_pics_folder)
            shutil.copyfile(fn_jpg_from, fn_jpg_to)
            if os.path.exists(fn_nef_from):
                print 'NEF of %s exists as well; also copying' % (picture)
                shutil.copyfile(fn_nef_from, fn_nef_to)