import openpyxl import os, sys from shutil import copyfile from datetime import datetime from dotenv import load_dotenv print("start rename_photo version 0.1") # Load variable from .env try: env_file = sys.argv[1] except IndexError: env_file = './environment.env' if os.path.exists(env_file): load_dotenv(dotenv_path=env_file) prefix = F"_{os.environ.get('PREFIX')}" if os.environ.get('PREFIX') is not None else '' 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()))) def check_config(): if os.environ.get('PHOTO_FROM') is None or not os.path.exists(os.path.join(os.environ.get('PHOTO_FROM').replace('\\', '/'))): raise FileNotFoundError("Не указана директория с фото") if os.environ.get('FILE') is None or not os.path.exists(os.environ.get('FILE')): raise FileNotFoundError('Не указана файл с данными') def get_list_photo() -> list[str]: list_files = [] for address, _, files in os.walk(os.path.join(os.environ.get('PHOTO_FROM').replace('\\', '/'))): for file in files: list_files.append(os.path.join(address, file)) return list_files def main(): check_config() if not os.path.exists(photo_to): os.mkdir(photo_to) try: excel_data = openpyxl.load_workbook(os.environ.get('FILE')) worksheet = excel_data.active for row in range(1, worksheet.max_row+1): column_tabn, column_fio = (1, 2) if os.environ.get('SWAP') not in 'False' else (2, 1) tabn = worksheet.cell(row=row, column=column_tabn).value fio = worksheet.cell(row=row, column=column_fio).value try: file = list(filter(lambda x: str(int(tabn)) in x, get_list_photo()))[0] print(os.path.join(photo_to, F"{fio}{prefix}.JPG")) copyfile(file, os.path.join(photo_to, F"{fio}{prefix}.JPG")) except ValueError: pass except TypeError: pass except IndexError: pass except openpyxl.utils.exceptions.InvalidFileException: raise openpyxl.utils.exceptions.InvalidFileException('Не правильный формат, поддерживаемые форматы: .xlsx, .xlsm, .xltx, .xltm') if __name__ == "__main__": try: main() except KeyboardInterrupt: print("bye bye")