Created
February 28, 2016 18:24
-
-
Save berlotto/3bb1e002120e245a94b8 to your computer and use it in GitHub Desktop.
Script que percorre um diretório, recursivamente e copia para outro diretório, organizado por ano/mes, somente arquivos de imagem (jpg/png/jpeg/gif)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- encoding: utf-8 -*- | |
| #----------------------------------------------------# | |
| # Title: Separador de Fotos | |
| # Author: Sérgio Berlotto <[email protected]> | |
| # Date: 28/Fev/2016 | |
| # Script que percorre um diretório, recursivamente e | |
| # deposita em outro diretório, organizado por ano/mes | |
| # somente arquivos de imagem (jpg/png/jpeg/gif) | |
| # | |
| # Usage: separafotos.py /diretorio/de/origem /diretorio/de/destino | |
| #----------------------------------------------------# | |
| import os | |
| import sys | |
| import re | |
| import shutil | |
| import exifread | |
| if len(sys.argv) < 3: | |
| print("É necessário informar ORIGEM e DESTINO!") | |
| exit(1) | |
| ORIGEM = sys.argv[1] | |
| DESTINO = sys.argv[2] | |
| FOTOS = ("jpg","png","jpeg","gif") | |
| ext = re.compile("(\.jpg|\.png|\.gif|\.jpeg)$", flags=re.IGNORECASE) | |
| if not os.path.isdir(ORIGEM): | |
| print("'%s' não é um diretório") | |
| exit(1) | |
| if not os.path.isdir(DESTINO): | |
| print("Criando pasta de destino %s" % DESTINO) | |
| os.makedirs(DESTINO, exist_ok=True) | |
| def makedir(dirname): | |
| tdir, file =os.path.split(dirname) | |
| if not os.path.isdir(tdir): | |
| os.makedirs(tdir, exist_ok=True) | |
| def copiagenerico(fotofile): | |
| #teoricamente é só uma imagem qq | |
| filedir, photoname = os.path.split(fotofile) | |
| new_local = os.path.join(DESTINO,"images",photoname) | |
| makedir(new_local) | |
| shutil.copy2(fotofile, new_local) | |
| for root, dirs, files in os.walk(ORIGEM): | |
| fotos = [ os.path.join(root, x) for x in files if ext.search(x) ] | |
| if fotos: | |
| for fotofile in fotos: | |
| tags = {} | |
| with open(fotofile, 'rb') as f: | |
| tags = exifread.process_file(f) | |
| if tags: | |
| #Teoricamente é uma FOTO | |
| try: | |
| data = str(tags["EXIF DateTimeOriginal"]) # 2014:05:08 12:25:29 @ 518 | |
| ano, mes = re.search(r"(\d+):(\d+)", str(tags['EXIF DateTimeOriginal']) ).groups() | |
| filedir, photoname = os.path.split(fotofile) | |
| new_local = os.path.join(DESTINO,ano,mes,photoname) | |
| makedir(new_local) | |
| shutil.copy2(fotofile, new_local) | |
| except KeyError as e: | |
| # Se não acha a data da foto, coloca em diretório separado | |
| copiagenerico(fotofile) | |
| else: | |
| copiagenerico(fotofile) | |
| print("Copy image files DONE!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment