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

Python拆分读取的文本行后如何去除换行符避免分号单独换行

问题解决方法

问题根因

逐行读取文本文件时,前3行末尾自带换行符\n,会被完整读取到NE变量中,拼接命令时换行符会被带到NE_Name和末尾分号之间,导致分号单独换行。文件最后一行默认无末尾换行符,因此输出符合预期。

修复方案

读取每行后先移除末尾的换行符再做拆分,修改后代码如下:

import tkinter as tk
import tkinter.filedialog


def tester():

    def script (TL1_Command):
        print ("%s\r" %(TL1_Command) )

    root = tk.Tk()
    root.attributes("-topmost", True) 
    root.withdraw()
    file = tkinter.filedialog.askopenfilename()
    
    with open(file,"r") as fh:
        for line in fh:
            # 移除行尾换行符
            line = line.rstrip('\n')
            IP,UID,PWD,NE = line.split(",")
##            print (IP)
##            print (PWD)
##            print (UID)
##            print (NE)
            script("ED-TL1GW:%s:SHELF-%s:TAG6:::GNE=%s,RNE=%s;"
                   %(IP,PWD, UID, NE) )

if __name__ == "__main__":
    tester()

补充说明

如果后续读取的行可能存在末尾空格,也可以用strip()方法同时移除首尾空白字符,只要确保原始文件内容里字段首尾没有有效空格即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:27:06