對 Dropbox 相片資料夾依月份整理收納

設定

  • 把下面這段 Python Source Code 另存成一個 py 檔。
  • 放在 /Dropbyx/Folder/Camera Uploads/ 底下。
  • 將 py 檔設成以 python.exe (python2、python3 皆可) 開啓。

執行

  • 打開 Camera Uploads Folder 。
  • 點兩下 py 檔。

行為

依照 Dropbox 的相片命名規則,將照片移到對應的月份底下。ex: 2014-04-04 09.17.54.png 會放在 2014-04 的資料夾下(自動建立)

Code

'''
'  @ author: OT Chen
'  @ last modified: 2014-04-10
'  @ contact: ot32em@gmail.com
'''

''' If you want to add more media extension detect, please add that to follow media_list var. '''
media_list = '|'.join( map( str, ('gif','jpg', 'png', 'mov', 'avi', 'wmv') ) )

import os
import re
import filecmp

def is_media_by_dropbox_naming( filename ):
    return re.match('^\d{4}-\d{2}-\d{2} \d{2}[\.|:]\d{2}[\.|:]\d{2}( HDR)?(\-\d{0,2})?.(' + media_list + ')$', filename )
        
def dir_name_by_month(filename):
    ''' sample: `[2014]-[04]-[05 21.23.20.jpg]` -> parsed as `[0]-[1]`=`2014-04` '''
    filename = filename.split('-')
    return filename[0] + "-" + filename[1]

def make_dir_if_not_exist( dir_name ):
    if not os.path.exists( dir_name ) :
        os.mkdir( dir_name )
        print('New directory "' + dir_name + '" has been created!')

def assert_dir(dir_name):
    if not os.path.isdir( dir_name ) :
        print("Error! File: " + dir_name + " should be a directory." )
        raise IOError

def prepare_directory(filename):
    dir_name = dir_name_by_month(filename)
    make_dir_if_not_exist(dir_name)
    assert_dir(dir_name)
    return dir_name
        
def handle_name_conflit(filename, dest_fullpath):
    if not filecmp.cmp(filename, dest_fullpath):
        ''' Media contents are different. Unable to handle... '''
        print('Error: Name conflicts with two different content files. Source file name: %s. Conflict file name: %s.' %(filename, dest_fullpath))
    else:
        ''' Identical content. Let user decide ignore or delete the replica. '''
        call = raw_input('"%s" has a identical copy in directory "%s/".\nDelete or Skip? D/S [S]' % (filename, dirname))
        if call.strip().lower() in ['d', 'delete']:
            os.remove(filename)
            print('Deleted "%s".' % filename)
        else:
            print('Skiped "%s".' % filename)
        
def move_file(filename):    
    dirname = prepare_directory(filename)
    dest_fullpath = os.path.join(dirname, filename)
    if os.path.exists(dest_fullpath):
        ''' Destination path already exists a file... '''
        handle_name_conflit() 
        return 0
        
    os.rename(filename, dest_fullpath) # move file to folder

    print("`%s` has moved to `%s`." % (filename, dest_fullpath))
    return 1
    
if __name__ == '__main__':
    c = 0
    cwd = '.'
    for filename in os.listdir(cwd):
        if os.path.isdir(filename):
            continue
        if not is_media_by_dropbox_naming(filename):
            continue
        c += move_file(filename)      
    print("Total " + str(c) + " files categorized by month.") 
comments powered by Disqus