Skip to content

Instantly share code, notes, and snippets.

@stefanedwards
Created August 4, 2017 15:46
Show Gist options
  • Save stefanedwards/4f57b3a83a5972d79b4812359bae607f to your computer and use it in GitHub Desktop.
Save stefanedwards/4f57b3a83a5972d79b4812359bae607f to your computer and use it in GitHub Desktop.
Copies photos from a folder, such as the DCIM folder of a digital camera, to a Dropbox folder, renaming the files according to their creation date in the process.
#!/usr/bin/python2.7
#############################
## Author: Stefan McKinnon Edwards <sme@iysik.com>
## Date: May 2013
## Revision: 1
## Description:
## Copies photos from a folder, such as the DCIM folder of a digital
## camera, to a Dropbox folder, renaming the files according to their
## creation date in the process.
#############################
from __future__ import print_function
import os
import shutil
import argparse
from glob import glob
import time
import sys
from Path import Path
class FileNotFoundException(Exception):
pass
class FileAlreadyExistsException(Exception):
pass
def copy_file(orig, destdir, fmt='%Y-%m-%d %H.%M.%S'):
'''
Copies the file `orig` to a dir (`destdir`), renaming it in the proces.
Returns destination filename.
'''
orig = Path(orig)
if not orig.exists:
raise FileNotFoundException(orig)
newname = time.strftime('%Y-%m-%d %H.%M.%S', time.gmtime(orig.ctime))
dest = destdir.append(newname+'.'+orig.ext)
if dest.exists:
raise FileAlreadyExistsException(dest)
shutil.copy(orig, dest)
return dest
def main(source, destdir):
print('Copying from {} to {}.'.format(source.abspath, destdir.abspath))
files = (f for f in glob(source.append('*')) if f.endswith('.jpg') or f.endswith('.JPG') or f.endswith('.AVI'))
for f in files:
try:
dest = copy_file(f, destdir)
except FileNotFoundException:
print('{} suddenly disappeared?'.format(f))
except FileAlreadyExistsException as e:
print('File {} already found as {}.'.format(f, e.message))
except Exception as e:
print('Other error:', e)
raise
else:
print('Copied {} to {}.'.format(f, dest))
return 0
description = '''Copies photos from a folder, such as the DCIM folder of a digital
camera, to a Dropbox folder, renaming the files according to their
creation date in the process.'''
dropbox = Path('/home/stefan/Dropbox/Camera Uploads')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=description)
parser.add_argument('sourcedir', nargs='?', default='.', help='Directory to copy from.', type=Path)
parser.add_argument('-d','--destdir',dest='destdir', default=dropbox, type=Path, help='Destination directory. Must exist.')
args = parser.parse_args(sys.argv[1:])
#print(args.sourcedir.abspath)
#print(sys.argv, args)
st = main(args.sourcedir, args.destdir)
sys.exit(st)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment