合并目录下的txt文件内容
import os
def merge_txt_files(txt_dir_path, txt_merged_path):
# 将所有文件的内容写入输出文件
with open(txt_merged_path, 'w', encoding='utf-8') as f:
# 遍历指定目录下的所有文件
for file_name in os.listdir(txt_dir_path):
if file_name.endswith(".txt"):
file_path = os.path.join(txt_dir_path, file_name)
with open(file_path, 'r', encoding='utf-8') as ff:
content = ff.read()
f.write(content)
# 在每个文件内容之间添加两行空白行作为分隔
# f.write('\n' * 2)
if __name__ == "__main__":
txt_dir_path = "test_1" # 更改为实际目录路径
txt_merged_path = "test_1_merged.txt" # 输出文件名
merge_txt_files(txt_dir_path, txt_merged_path)
标签:__,合并,dir,file,path,txt,目录,merged
From: https://blog.csdn.net/familytaijun/article/details/140927354