합칠파일들이 한 폴더에 있는 경우다.
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)
'IT기타' 카테고리의 다른 글
크롬 콘솔창 활용, 데이터 수집(javascript) 후 다운로드 받기 (0) | 2024.07.28 |
---|---|
시퀀스 다이어그램 작성 (무료사이트 이용) (0) | 2024.07.27 |
로그인된 상태에서 스크랩 자동(selenium, python) (0) | 2024.07.25 |
what's different BeautifulSoup and Selenium (0) | 2024.07.24 |
(Selenium 사용) 메인메이지 -> 링크 리스트 -> 상세데이터 수집 (페이징 데이터수집) (2) | 2024.07.24 |