파이썬 (Python)/파이썬 공통

[Python] 파일 이름 일괄변경 툴 만들기 (폴더 이름과 같게)

Minkyu Lee 2024. 2. 25. 21:48

개요

회사 업무상, 폴더 안의 파일들의 이름을, 특정 규칙대로 바꿔줘야하는 경우가 생겼다.

시중에 여러 툴들이 있으나 모든 폴더를 일괄적으로 간단히 바꾸는 툴이 없어 만들게 됐다.

 

특정 규칙은 아래 서술한 코드 최상단에 적어놓았다.

 

결과

 

코드

'''
현 경로에서 폴더들을 찾는다.
각 폴더 안의 파일에 접근한다.

파일의 확장자와 맨뒤 숫자 4자리만 남긴다.
파일들의 이름은 폴더 이름으로 변경한다.
뒤에 원래 숫자와 확장자를 붙인다.
---
'''

from  tkinter import *
import os
import re
import sys

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

def center_window(window, width, height):
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()

    x = (screen_width - width) // 2
    y = (screen_height - height) // 2

    window.geometry(f"{width}x{height}+{x}+{y}")
   
def rename_files_in_folders():
    # 현재 디렉토리에서 폴더를 찾기
    folders = [folder for folder in os.listdir() if os.path.isdir(folder)]

    # 각 폴더 내의 파일들에 접근하여 이름 변경
    for folder in folders:
        folder_path = os.path.join(os.getcwd(), folder)
       
        # 폴더 내의 파일들 가져오기
        files = [file for file in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, file))]

        # 각 파일의 이름을 폴더 이름으로 변경
        for file in files:
            old_path = os.path.join(folder_path, file)
           
            # 파일 이름에서 확장자와 맨 뒤의 숫자 4자리 추출
            base_name, file_extension = os.path.splitext(file)
            match = re.search(r'\d{4}$', base_name)
            if match:
                last_digits = match.group()
            else:
                last_digits = ''

            # 새로운 파일 이름 생성 (폴더 이름 + 맨 뒤의 숫자 4자리 + 확장자)
            new_name = f"{folder}_{last_digits}{file_extension}"
            new_path = os.path.join(folder_path, new_name)

            # 파일 이름 변경
            os.rename(old_path, new_path)
            #print(f"Renamed: {old_path} -> {new_path}")

# 창 설정
root = Tk()
root.title("이름 변경")

window_width = 300
window_height = 200
root.geometry(f"{window_width}x{window_height}")
center_window(root, window_width, window_height)

# 레이블
label_text = Label(root, text="...")
label_text.pack()

photo = PhotoImage(file=resource_path("boring.png"))
label_image = Label(root, image=photo)
label_image.pack()

# 버튼
def btn_cmd():
    # 동작
    rename_files_in_folders()
   
    # 텍스트 변경
    label_text.config(text="완료")

    # 이미지 변경
    global photo2
    photo2 = image=PhotoImage(file=resource_path("smile.png"))
    label_image.config(image=photo2)

btn = Button(root, text="실행", command=btn_cmd)
btn.pack()

# 실행
root.mainloop()