程式碼:
import os def merge_srt_files(source_dir, output_file): """ 合併指定目錄及其子目錄下的所有.srt檔案到一個新檔案中。 :param source_dir: 源目錄路徑 :param output_file: 輸出檔案路徑 """ # 確保輸出檔案的目錄存在 os.makedirs(os.path.dirname(output_file), exist_ok=True) # 開啟輸出檔案準備寫入 with open(output_file, 'w', encoding='utf-8') as outfile: # 遍歷目錄 for root, dirs, files in os.walk(source_dir): for file in files: if file.endswith('.srt'): file_path = os.path.join(root, file) with open(file_path, 'r', encoding='utf-8') as infile: # 讀取srt檔案內容 content = infile.read() # 寫入到輸出檔案,每個檔案之間留一個空行作為分隔 outfile.write(content) outfile.write('\n\n') # 指定源目錄和輸出檔案 source_directory = r"C:\caijian\tengman" output_srt_file = r"C:\caijian\tengman\merged_output.srt" # 呼叫函式執行合併 merge_srt_files(source_directory, output_srt_file) print(f"所有.srt檔案已合併到 {output_srt_file}")