Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,将.write()中的变量置于新行后的字符串部分_Python_Newline - Fatal编程技术网

在Python中,将.write()中的变量置于新行后的字符串部分

在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

我对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(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"))