代码:
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}")
标签:文件,srt,python,source,file,output,os From: https://www.cnblogs.com/jingzaixin/p/18453614