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

Python合并不同文件字符串写入输出文件仅保留单一行问题求助

换行问题根源及解决方法

问题原因

  • 调用read()方法读取文件全量内容时,会保留文件末尾自带的换行符\n
  • 迭代文件对象读取每一行时,拿到的单行内容也默认携带行尾的换行符\n
    你看到的自动换行不是print()或者write()方法额外添加的,是读取到的变量本身就包含换行符。

修正方案

你可以在读取内容时直接去掉末尾的换行符,推荐使用with语句自动管理文件的打开关闭,避免遗漏close()操作,修正后代码如下:

import os

# 读取文件时直接去掉末尾换行符
with open('eannuli_spec_prova_ciao.reg','r') as eannuli:
    # 仅取第一行,和原代码里break逻辑一致
    ean = eannuli.readline().rstrip('\n')

with open('23849_fov_c7_ciao.reg','r') as fov_c7:
    fov7 = fov_c7.read().rstrip('\n')

with open('psrc-ciao_mod.reg','r') as psr:
    psrc = psr.read().rstrip('\n')

i = 1
while os.path.exists(f'region{i}.reg'):
    i += 1

# 合并内容写入
with open(f'region{i}.reg', 'w') as region:
    content = f"{fov7}*{ean}{psrc}"
    region.write(content)

补充说明

你之前用write()失败也是同样的原因,只要提前把变量里的末尾换行符移除,直接write(fov7 + '*' + ean + psrc)也可以实现一行输出的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:57:02