W Pub: Python Renamer

Código fuente

Necesita la librería EXIF.py que podrás encontrar aquí

  1.  
  2. #!/usr/bin/env python
  3. #
  4. # RenamerPy Version 1.0 - Rename large JPG file with EXIF or file time attributes
  5. #
  6. # User EXIF.py library form Ianaré Sévi at http://sourceforge.net/projects/exif-py-3/
  7. #
  8. # CopyLeft (c) 2013 Alex Bergonzini
  9. #
  10. # Redistribution and use in source and binary forms, with or without
  11. # modification, are permitted provided that the following conditions
  12. # are met:
  13. #
  14. #  1. Redistributions of source code must retain the above copyright
  15. #     notice, this list of conditions and the following disclaimer.
  16. #
  17. #  2. Redistributions in binary form must reproduce the above
  18. #     copyright notice, this list of conditions and the following
  19. #     disclaimer in the documentation and/or other materials provided
  20. #     with the distribution.
  21. #
  22. #  3. Neither the name of the authors nor the names of its contributors
  23. #     may be used to endorse or promote products derived from this
  24. #     software without specific prior written permission.
  25. #
  26. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  27. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  28. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  29. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  30. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  31. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  32. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  33. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  34. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  35. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  36. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37. import os, time, sys, getopt, shutil
  38. import EXIF
  39.  
  40.  
  41. path=''
  42. path_d=''
  43. option_ym=True
  44. option_y=False
  45. option_m=False
  46. option_t=False
  47.  
  48. #--[ Convertimos de numeros a dos posiciones
  49. def convert_hms(valor):
  50.     tmp=str(valor)
  51.     if valor<=9:
  52.         tmp="0"+tmp
  53.     return tmp
  54.  
  55. #--[ Buscamos los ficheros por subdirectorios
  56. def ficheros(directorio):
  57.     mat=[]
  58.     fichero=[]
  59.     for dirname, dirnames, filenames in os.walk(directorio):
  60.  
  61.         for filename in filenames:
  62.             fichero=[]
  63.             nom=os.path.join(dirname, filename)
  64.             nom_up=nom.upper()
  65.             if nom_up.find('JPG' or 'JPEG')>0:
  66.                 fichero.append(os.path.join(dirname,""))
  67.                 fichero.append(os.path.join(filename,""))
  68.                 fichero.append(os.path.join(dirname, filename))
  69.                 fecha=time.ctime(os.path.getmtime(os.path.join(dirname, filename)))
  70.                 print(fecha)
  71.                 fechas=time.strptime(fecha,'%a %b %d %H:%M:%S %Y')
  72.                 fichero.append(str(fechas[0])+convert_hms(fechas[1])+
  73.                 convert_hms(fechas[2])+convert_hms(fechas[3])+
  74.                 convert_hms(fechas[4])+convert_hms(fechas[5]))
  75.                 mat.append(fichero)
  76.  
  77.     return mat
  78.  
  79. def hardwork(mi_dir,destino_dir):
  80.     global option_m, option_y, option_ym, option_t
  81.     lista=ficheros(mi_dir)
  82.     for n in range(0, len(lista)):
  83.         file=lista[n]
  84.         f=open(file[2],"rb")
  85.         try:
  86.             tags=EXIF.process_file(f)
  87.             encontrado=False
  88.  
  89. #--[ Buscamos las etiquetas
  90.             if 'EXIF DateTimeOriginal' in tags:
  91.                 fecha=tags['EXIF DateTimeOriginal']
  92.                 encontrado=True
  93.             if 'DateTimeOriginal' in tags:
  94.                 fecha=tags['DateTimeOriginal']
  95.                 encontrado=True
  96.             if 'DateTime' in tags:
  97.                 fecha=tags['DateTime']
  98.                 encontrado=True
  99.  
  100.             if encontrado:
  101.                 fechas=str(fecha)
  102.                 fechas=fechas.replace(':','')
  103.                 fechas=fechas.replace(' ','')
  104.                 file[3]= fechas[2:-1]
  105.  
  106. #Comprobamos si el fichero ya existe
  107.             origen_f=file[2]
  108.             real_destino=os.path.join(destino_dir,file[3][0:4])
  109.  
  110.             if not os.path.isdir(real_destino):
  111.                 os.mkdir(real_destino)
  112.             real_destino=os.path.join(real_destino,"X")
  113.             real_destino=real_destino[0:-1]
  114.  
  115.             real_destino=real_destino+file[3][0:6]
  116.             if not os.path.isdir(real_destino):
  117.                 os.mkdir(real_destino)
  118.             real_destino=os.path.join(real_destino,"X")
  119.             real_destino=real_destino[0:-1]
  120.  
  121.  
  122.             destino=real_destino+file[3]+'.jpg'
  123.  
  124.             x=0
  125.             while os.path.isfile(destino)==True:
  126.                 x_tmp=convert_hms(x)
  127.                 destino = real_destino+file[3][0:-2]+x_tmp+'.jpg'
  128.                 x+=1
  129.             print("Processing "+origen_f+"->"+destino)
  130.             if option_t==True:
  131.                 if option_m==True:
  132.                     shutil.move(origen_f,destino)
  133.                 else:
  134.                     shutil.copy(origen_f,destino)
  135.         finally:
  136.             f.close()
  137.  
  138. #hardwork('t:\\hola\\')
  139.  
  140. def print_header():
  141.     print("** RenamerPy v1.0 ** Easy Renamer for your photo collection "+
  142.             "** CopyLeft 2013 Bergonzini at http://www.bergonzini.com\n\n")
  143.  
  144. def print_help():
  145.     print_header()
  146.     print("Options: \n"+
  147.           "   -p   Path with the photo collection to rename\n"+
  148.           "   -d   Path to save the renamed photos\n"+
  149.           "   -Y   Create in the destination folder subfolders like YYYY/YYYYMM/ \n"+
  150.           "   -y   Like -Y option but only YYYY/ \n"+
  151.           "   -m   Move files instead copy\n"+
  152.           "   -t   Test mode don''t move/copy only\n")
  153.  
  154. def command_line():
  155.     global path, option_m, option_y, option_ym, option_t
  156.     path_d=''
  157.     try:
  158.         opts, args = getopt.getopt(sys.argv[1:],"hp:d:yYmt")
  159.     except getopt.GetoptError:
  160.         print_help()
  161.  
  162.     for opt, arg in opts:
  163.         if opt == '-h':
  164.             print_help()
  165.             exit()
  166.         elif opt == "-p":
  167.             path=arg
  168.         elif opt == "-d":
  169.             path_d=arg
  170.         elif opt =="-Y":
  171.             option_ym=True;
  172.         elif opt == "-y":
  173.             option_y=True
  174.         elif opt == "-t":
  175.             option_t=True
  176.         elif opt == '-m':
  177.             option_m=True;
  178.  
  179.  
  180.     if not os.path.isdir(path):
  181.         print_header()
  182.         print("[ERROR] Origen path not found! "+path)
  183.     else:
  184.         if not os.path.isdir(path_d):
  185.            os.mkdir(path_d)
  186.         if path!="" and path_d!="":
  187.             print_header()
  188.             print("Processing "+path)
  189.             hardwork(path,path_d)
  190.         else:
  191.             print_help()
  192.  
  193.  
  194. command_line()

(:sourcend:)