IT기타

여러 txt 파일 한 파일로 합치기(python)

emilyyoo 2024. 7. 26. 15:02
728x90

합칠파일들이 한 폴더에 있는 경우다.


import os

def merge_text_files(folder_path, output_file):
    # 폴더 내 모든 텍스트 파일 목록 가져오기
    files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]
    
    # 결합된 텍스트를 저장할 변수
    combined_text = ""
    total_files = len(files)
    
    # 각 파일을 읽어서 결합
    for file in files:
        file_path = os.path.join(folder_path, file)
        with open(file_path, 'r', encoding='utf-8') as f:
            file_content = f.read()
            combined_text += file_content + "\n"  # 각 파일의 내용 뒤에 줄바꿈 추가
            combined_text += f"=====================================Title: {file}\n"  # 파일 제목 추가
        
            print(f"Read {len(file_content)} characters from {file}")
    
    # 결합된 텍스트를 새 파일에 저장
    with open(output_file, 'w', encoding='utf-8') as out_file:
        out_file.write(combined_text)
    
    print(f"\nTotal {total_files} files combined.")
    print(f"Combined text length: {len(combined_text)} characters")

# 사용 예시


folder_path = r'~~~~~~~~~~'  # 텍스트 파일들이 있는 폴더 경로
output_file = r'~~~~~~~~\결합된 텍스트파일.txt'  # 결합된 텍스트 파일저장 위치. 
merge_text_files(folder_path, output_file)

728x90