rename_photo_from_xlsx.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import openpyxl
  2. import os, sys
  3. from shutil import copyfile
  4. from datetime import datetime
  5. from dotenv import load_dotenv
  6. print("start rename_photo version 0.1")
  7. # Load variable from .env
  8. try:
  9. env_file = sys.argv[1]
  10. except IndexError:
  11. env_file = './environment.env'
  12. if os.path.exists(env_file):
  13. load_dotenv(dotenv_path=env_file)
  14. prefix = F"_{os.environ.get('PREFIX')}" if os.environ.get('PREFIX') is not None else ''
  15. photo_to = os.environ.get('PHOTO_TO') if os.environ.get('PHOTO_TO') else os.path.join(os.path.dirname(__file__), str(datetime.timestamp(datetime.now())))
  16. def check_config():
  17. if os.environ.get('PHOTO_FROM') is None or not os.path.exists(os.path.join(os.environ.get('PHOTO_FROM').replace('\\', '/'))):
  18. raise FileNotFoundError("Не указана директория с фото")
  19. if os.environ.get('FILE') is None or not os.path.exists(os.environ.get('FILE')):
  20. raise FileNotFoundError('Не указана файл с данными')
  21. def get_list_photo() -> list[str]:
  22. list_files = []
  23. for address, _, files in os.walk(os.path.join(os.environ.get('PHOTO_FROM').replace('\\', '/'))):
  24. for file in files:
  25. list_files.append(os.path.join(address, file))
  26. return list_files
  27. def main():
  28. check_config()
  29. if not os.path.exists(photo_to):
  30. os.mkdir(photo_to)
  31. try:
  32. excel_data = openpyxl.load_workbook(os.environ.get('FILE'))
  33. worksheet = excel_data.active
  34. for row in range(1, worksheet.max_row+1):
  35. column_tabn, column_fio = (1, 2) if os.environ.get('SWAP') not in 'False' else (2, 1)
  36. tabn = worksheet.cell(row=row, column=column_tabn).value
  37. fio = worksheet.cell(row=row, column=column_fio).value
  38. try:
  39. file = list(filter(lambda x: str(int(tabn)) in x, get_list_photo()))[0]
  40. print(os.path.join(photo_to, F"{fio}{prefix}.JPG"))
  41. copyfile(file, os.path.join(photo_to, F"{fio}{prefix}.JPG"))
  42. except ValueError:
  43. pass
  44. except TypeError:
  45. pass
  46. except IndexError:
  47. pass
  48. except openpyxl.utils.exceptions.InvalidFileException:
  49. raise openpyxl.utils.exceptions.InvalidFileException('Не правильный формат, поддерживаемые форматы: .xlsx, .xlsm, .xltx, .xltm')
  50. if __name__ == "__main__":
  51. try:
  52. main()
  53. except KeyboardInterrupt:
  54. print("bye bye")