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
相关产品推荐
相关产品推荐

