在Python中,将.write()中的变量置于新行后的字符串部分
我对Python比较陌生。所以请原谅我的天真。在尝试将字符串写入文件时,将变量后的字符串部分放在新行上,并且不应将其删除。顺便说一句,我正在使用python 2.6.5在Python中,将.write()中的变量置于新行后的字符串部分,python,newline,Python,Newline,我对Python比较陌生。所以请原谅我的天真。在尝试将字符串写入文件时,将变量后的字符串部分放在新行上,并且不应将其删除。顺便说一句,我正在使用python 2.6.5 arch = subprocess.Popen("info " + agent + " | grep '\[arch\]' | awk '{print $3}'", shell=True, stdout=subprocess.PIPE) arch, err = arch.communicate() strarch = str(a
arch = subprocess.Popen("info " + agent + " | grep '\[arch\]' | awk '{print $3}'", shell=True, stdout=subprocess.PIPE)
arch, err = arch.communicate()
strarch = str(arch)
with open ("agentInfo", "a") as info:
info.write("Arch Bits: " + strarch + " bit")
info.close()
os.system("cat agentInfo")
期望输出:
"Arch Bits: 64 bit"
实际产量:
"Arch Bits: 64
bits"
看起来str(arch)
有一个尾随新行,您可以使用str.strip
或str.rstrip
删除该行:
strarch = str(arch).strip() #removes all types of white-space characters
或:
您也可以在此处使用:
请注意,不需要
info.close()
strarch = str(arch).rstrip('\n') #removes only trailing '\n'
strarch = str(arch).rstrip('\n')
info.write("{}: {} {}".format("Arch Bits", strarch, "bits"))