본문 바로가기
귀펀치토끼는 부서지지 않는다.
주소(D)
영웅은 공부 따원 안 한다네

[파이썬] 파일명 일치하면 파일 옮기기

import os
import shutil

# 프로젝트 루트 디렉토리 경로
project_root = '/Users/BlackPaw/Downloads/ai-python-sample-master/sound/'

# 프로젝트 루트 디렉토리에서 모든 wav 파일의 경로를 가져옵니다.
def find_wav_files(root_dir):
    wav_files = []
    for root, _, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.wav'):
                wav_files.append(os.path.join(root, file))
    return wav_files

# 주어진 디렉토리에서 모든 text 파일의 경로를 가져옵니다.
def find_text_files(directory):
    text_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.txt'):
                text_files.append(os.path.join(root, file))
    return text_files

# wav 파일 경로에서 파일 이름(확장자 제외)을 추출합니다.
def get_wav_filename_without_extension(wav_file_path):
    return os.path.splitext(os.path.basename(wav_file_path))[0]

# 주어진 text 파일을 해당하는 wav 파일이 있는 폴더로 이동시킵니다.
def move_text_file_to_wav_folder(text_file, wav_file):
    text_filename = os.path.basename(text_file)
    target_folder = os.path.dirname(wav_file)
    target_text_path = os.path.join(target_folder, text_filename)
    shutil.move(text_file, target_text_path)

# 프로젝트 루트 디렉토리에서 모든 wav 파일 목록을 가져옵니다.
wav_files = find_wav_files(project_root)

# 프로젝트 루트 디렉토리에서 모든 text 파일 목록을 가져옵니다.
text_files = find_text_files(project_root)

# text 파일과 wav 파일 이름을 비교하여 이동합니다.
for text_file in text_files:
    text_filename_without_extension = os.path.splitext(os.path.basename(text_file))[0]
    matching_wav_file = None
    for wav_file in wav_files:
        wav_filename_without_extension = get_wav_filename_without_extension(wav_file)
        if text_filename_without_extension == wav_filename_without_extension:
            matching_wav_file = wav_file
            break

    # 일치하는 wav 파일이 있으면 이동
    if matching_wav_file:
        move_text_file_to_wav_folder(text_file, matching_wav_file)
    # 일치하는 wav 파일이 없으면 이동할 폴더 지정 (예: 'unmatched')
    else:
        unmatched_folder = os.path.join(project_root, 'unmatched')
        if not os.path.exists(unmatched_folder):
            os.makedirs(unmatched_folder)
        target_path = os.path.join(unmatched_folder, os.path.basename(text_file))
        shutil.move(text_file, target_path)

print("작업이 완료되었습니다.")
완료
내 컴퓨터