在python中使用列表时如何避免新行

2024-10-01 15:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图避免在输出文件pythonoutputscript.txt中创建新行。我希望避免在从输入文本文件映射的(变量/列表)中开始新行(抱歉,是python的新成员)。在(par01[51])(par01[53])前面有一个我可以映射的字符来防止这种情况发生吗?提前感谢您的帮助

我的程序的当前输出:

EthernetCurrentConnectionInfo 
**NEWLINE**CommunicationsSendAndWait "ADDMASTER 11 
**NEWLINE**10.53.40.99 
**NEWLINE**\r",5,true,>

我希望它输出:

EthernetCurrentConnectionInfo
**NEWLINE**CommunicationsSendAndWait "ADDMASTER 11 10.53.40.99 \r",5,true,>

我的代码:

##INFO
A1 == 1
##CONTENT IN
inFile = open('pythoninputscript.txt', 'rt')
par01 = inFile.readlines()
if A1 == 1:
    print(par01[0:3])

##ALTERATIONS OUT
outFile = open('pythonoutputscript.txt', 'wt')
outFile.write ("EthernetCurrentConnectionInfo\nCommunicationsSendAndWait 
\"ADDMASTER "+(par01[51])+(par01[53])+"\\r\",5,true,>\n")
outFile.close()

Tags: 文件txttrue列表a1newlineopeninfile
1条回答
网友
1楼 · 发布于 2024-10-01 15:35:19

使用三重引号版本作为模板更方便:

template = """EthernetCurrentConnectionInfo
CommunicationsSendAndWait "ADDMASTER {} {} \\r",5,true,>"""

并使用rstrip()去除值末尾的空白:

outFile.write(template.format(par01[51].rstrip(), par01[53].rstrip()))

{}标记的占位符将被par01[51]par01[53]中的值替换

相关问题 更多 >

    热门问题