이미지 파일 이름 기반 자동 분류 및 처리 스크립트

1. 이미지 파일명에서 첫 번째 언더스코어 이전 부분 삭제

지정된 폴더 내 모든 이미지 파일의 이름에서 첫 번째 언더스코어와 그 앞의 내용을 제거하고, 나머지 부분으로 파일명을 변경합니다.

import os

def remove_prefix_underline(directory):
    for filename in os.listdir(directory):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
            pos = filename.find('_')
            if pos != -1:
                new_name = filename[pos + 1:]
                old_path = os.path.join(directory, filename)
                new_path = os.path.join(directory, new_name)
                os.rename(old_path, new_path)
                print(f"이름 변경: {filename} → {new_name}")

folder_input = input("폴더 경로를 입력하세요: ")
remove_prefix_underline(folder_input)

2. 이미지 이름의 영문자만 추출하고, 최대 25자로 제한하여 소문자로 재이름

이미지 파일명에서 공백, 특수기호, 한글 등을 제거하고, 영문자만 남긴 후, 처음부터 25자까지 추출하여 소문자로 변환합니다. 중복 시 (1), (2) 등 추가 후 이름 변경.

import os
import re

def extract_and_truncate(filename):
    # 영문자만 남기고, 대소문자 구분 없애기
    cleaned = re.sub(r'[^A-Za-z]', '', filename).lower()
    return cleaned[:25]

def rename_images_with_limit(folder_path):
    if not os.path.isdir(folder_path):
        print("유효하지 않은 폴더입니다.")
        return

    processed_names = {}
    for file in os.listdir(folder_path):
        ext = os.path.splitext(file)[1].lower()
        if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
            continue

        base_name = extract_and_truncate(file)
        original_base = base_name
        counter = 1

        while base_name in processed_names.values() or os.path.exists(os.path.join(folder_path, base_name + ext)):
            base_name = f"{original_base}({counter})"
            counter += 1

        old_path = os.path.join(folder_path, file)
        new_path = os.path.join(folder_path, base_name + ext)
        try:
            os.rename(old_path, new_path)
            processed_names[file] = base_name + ext
        except OSError as e:
            print(f"오류 발생: {file} -> {new_path}: {e}")

    print("모든 파일 이름 수정 완료.")

if __name__ == "__main__":
    path = input("이미지 폴더 경로 입력: ")
    rename_images_with_limit(path)

3. Excel에서 특정 셀에 영문자만 추출하고, 최대 25자로 제한하는 수식

엑셀의 A2 셀에 포함된 텍스트에서 공백, 특수문자, 한글을 제거하고, 영문자만 남긴 뒤, 처음 25자만 추출합니다.

=LEFT(TEXTJOIN("", TRUE, IF(ISNUMBER(FIND(MID(SUBSTITUTE(A2," ",""), ROW(INDIRECT("1:"&LEN(SUBSTITUTE(A2," ","")))),1), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")), MID(SUBSTITUTE(A2," ",""), ROW(INDIRECT("1:"&LEN(SUBSTITUTE(A2," ","")))),1), "")), 25)

사용법: 위 수식은 A2 셀의 값을 처리하며, 복사해서 원하는 셀에 붙여넣으세요. 엔터 후 결과 확인.

4. 이미지 파일을 엑셀 정보 기반으로 자동 분류 및 폴더 생성

사용자가 지정한 원본 폴더, 타겟 폴더, 엑셀 파일, 열 번호를 기반으로 각 이미지 파일을 이름 기준으로 매칭하여 해당 행의 정보로 폴더 생성 후 이동하고, 폴더 내에 참고 정보를 담은 .txt 파일 생성.

import os
import shutil
import pandas as pd

def classify_images_by_excel():
    source_folder = input("원본 폴더 경로: ").strip()
    target_folder = input("목표 폴더 경로: ").strip()
    excel_file = input("Excel 파일 경로: ").strip()
    
    col_x = int(input("입력 열 번호 (X): ")) - 1
    col_y = int(input("이름 열 번호 (Y): ")) - 1
    col_z = int(input("텍스트 참조 열 번호 (Z): ")) - 1

    # 경로 유효성 검사
    if not os.path.exists(source_folder):
        raise FileNotFoundError(f"원본 폴더가 존재하지 않습니다: {source_folder}")
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)

    if not os.path.exists(excel_file):
        raise FileNotFoundError(f"Excel 파일이 존재하지 않습니다: {excel_file}")

    df = pd.read_excel(excel_file)
    max_col = max(col_x, col_y, col_z)
    if len(df.columns) <= max_col:
        raise IndexError("지정한 열 번호가 엑셀 범위를 초과했습니다.")

    # 파일 처리
    for file_name in os.listdir(source_folder):
        ext = os.path.splitext(file_name)[1].lower()
        if ext not in ['.jpg', '.jpeg', '.png']:
            continue

        # 이미지 이름의 앞부분 25자 영문자 추출
        clean_name = ''.join(c for c in file_name if c.isalpha())[:25]

        # 매칭되는 행 찾기
        match_row = df[df.iloc[:, col_x].astype(str).str.startswith(clean_name)]
        if match_row.empty:
            continue

        folder_name = str(match_row.iloc[0, col_y])
        dest_path = os.path.join(target_folder, folder_name)

        # 폴더 생성 (중복 시 생략)
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)

        # 파일 이동
        src_path = os.path.join(source_folder, file_name)
        shutil.move(src_path, os.path.join(dest_path, file_name))

        # txt 파일 생성 및 정보 기록
        txt_file = os.path.join(dest_path, f"{folder_name}.txt")
        if not os.path.exists(txt_file):
            with open(txt_file, 'w', encoding='utf-8') as f:
                content = str(match_row.iloc[0, col_z])
                f.write(content)

    print("모든 파일 처리 완료.")

if __name__ == "__main__":
    try:
        classify_images_by_excel()
    except Exception as e:
        print(f"오류 발생: {e}")

태그: python pandas Excel 파일 처리 이미지 분류

6월 14일 20:15에 게시됨