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

Python合并多个txt题库文件时追加内容不换行该如何调整代码?

问题原因

你当前的代码直接按字节拼接多个文件的内容,没有在不同文件的内容之间插入换行分隔符。如果前一个题库文件的最后一行末尾没有自带换行符,就会出现后一个文件的首行内容直接拼接在前一个文件尾行末尾的问题。

修复方案

方案1:保留二进制读写逻辑(最小改动)

仅需在每写完一个文件的内容后,主动向输出文件写入一个换行字节即可:

import glob
import shutil

def master_list():
    outfilename = "zMasterList.txt"
    # 通用换行字节,如需适配Windows标准换行可改为b'\r\n'
    line_break = b'\n'

    with open(outfilename, 'wb') as outfile:
        for filename in glob.glob('*.txt'):
            if filename == outfilename:
                continue
            with open(filename, 'rb') as readfile:
                shutil.copyfileobj(readfile, outfile)
                # 追加换行分隔两个文件内容
                outfile.write(line_break)

方案2:改为文本模式读写(更适配文本场景)

如果你的题库都是普通文本文件,用文本模式读写可以更好的适配不同编码、不同系统的换行格式,避免二进制读写可能出现的乱码问题:

import glob

def master_list():
    outfilename = "zMasterList.txt"
    # 可根据你的文件实际编码修改encoding参数,比如gbk、utf-8-sig
    with open(outfilename, 'w', encoding='utf-8') as outfile:
        for filename in glob.glob('*.txt'):
            if filename == outfilename:
                continue
            with open(filename, 'r', encoding='utf-8') as readfile:
                outfile.write(readfile.read())
                outfile.write('\n')

额外优化说明

如果需要避免部分文件末尾自带换行导致合并后出现多余空行,可以在写入新文件内容前,先判断输出文件当前末尾是否为换行符,仅当不存在换行时才插入分隔换行。

内容的提问来源于stack exchange,提问作者I am Jakoby

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:54:07