You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多文件合并为单个文件并插入文件间换行:Python脚本实现求助

解决文本文件合并后添加换行的问题

方案1:改进CMD命令实现

Windows自带的copy *.txt命令只会直接拼接文件内容,不会自动添加换行。可以用CMD的for循环配合type命令,为每个文件的内容后追加换行:

for %f in (*.txt) do type "%f" >> result.txt & echo. >> result.txt
  • for %f in (*.txt):遍历当前目录下所有txt文件
  • type "%f" >> result.txt:将当前文件内容追加到result.txt
  • echo. >> result.txt:在每个文件内容后添加一个换行

在Python中调用该命令的代码:

import os

path = r'C:\Users\CL\test'
os.chdir(path)

# 可选:清空已存在的result.txt,避免重复追加内容
if os.path.exists('result.txt'):
    os.remove('result.txt')

# 执行CMD命令,/c表示执行后关闭CMD窗口
os.system('cmd /c "for %f in (*.txt) do type "%f" >> result.txt & echo. >> result.txt"')

方案2:Python结合while循环实现

如果需要用Python的while循环完成合并并添加换行,不依赖CMD命令,可以用以下代码:

import os

path = r'C:\Users\CL\test'
os.chdir(path)

# 获取目录下所有txt文件
txt_files = [filename for filename in os.listdir() if filename.endswith('.txt')]
current_idx = 0

# 打开结果文件准备写入
with open('result.txt', 'w', encoding='utf-8') as result_f:
    # while循环遍历所有txt文件
    while current_idx < len(txt_files):
        file_path = txt_files[current_idx]
        # 读取当前文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            # 去除原文件末尾可能的多余换行,再添加一个换行写入结果
            content = f.read().rstrip('\n')
            result_f.write(content + '\n')
        current_idx += 1

这段代码通过while循环逐个读取每个txt文件的内容,去除原文件末尾可能存在的多余换行后,添加一个新换行写入结果文件,最终得到每个文件内容单独一行的效果。

内容的提问来源于stack exchange,提问作者panzers1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 10:42:31