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

Python遍历文件行拼接内容,如何消除重复部分的换行

Python 文件行内容自拼接问题解决

你遇到的问题核心是:从文件读取的每行末尾默认带有换行符\n,直接拼接会导致内容被换行拆分。以下是几种针对性的解决方法:

方法1:去除所有首尾空白(通用场景推荐)

使用strip()方法移除每行首尾的换行符、空格等空白字符,再拼接并添加空格:

with open('domains.txt','r') as f:
    for line in f:
        cleaned_line = line.strip()
        print(f"{cleaned_line} {cleaned_line}")

方法2:仅移除换行符(保留其他空白)

如果需要保留行首或行尾的空格,用rstrip('\n')精准去掉末尾的换行符:

with open('domains.txt','r') as f:
    for line in f:
        cleaned_line = line.rstrip('\n')
        print(f"{cleaned_line} {cleaned_line}")

方法3:替换换行符

直接把行内的换行符替换为空字符串:

with open('domains.txt','r') as f:
    for line in f:
        cleaned_line = line.replace('\n', '')
        print(f"{cleaned_line} {cleaned_line}")

问题根源说明

你原来的代码中,line变量实际是"string\n"这类带换行的字符串,拼接后变成"string\nstring\n",打印时会自动按换行符拆分,导致出现两行内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:48:11