rename_photo_from_xlsx.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import openpyxl
  2. import os, sys
  3. from shutil import copyfile
  4. from datetime import datetime
  5. from dotenv import load_dotenv
  6. # Load variable from .env
  7. try:
  8. env_file = sys.argv[1]
  9. except IndexError:
  10. env_file = os.path.join(os.path.dirname(__file__), 'environment.env')
  11. if os.path.exists(env_file):
  12. load_dotenv(dotenv_path=env_file)
  13. prefix = F"_{os.environ.get('PREFIX')}" if os.environ.get('PREFIX') is not None else ''
  14. photo_to = os.path.join(os.path.dirname(__file__), str(datetime.timestamp(datetime.now())))
  15. def check_config():
  16. print(os.path.exists(os.environ.get('FILE')))
  17. if os.environ.get('PHOTO_FROM') is None or not os.path.exists(os.environ.get('PHOTO_FROM')):
  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.environ.get('PHOTO_FROM')):
  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') 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. main()