Reputation: 257
I am relatively new to Python. So please excuse my naivety. While trying to write a string to a file, the portion of the string after the variable is put on a new line and it should not be. I am using python 2.6.5 btw
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")
Desireded output:
"Arch Bits: 64 bit"
Actual output:
"Arch Bits: 64
bits"
Upvotes: 1
Views: 758
Reputation: 251146
Looks like str(arch)
has a trailing new line, you can remove that using str.strip
or str.rstrip
:
strarch = str(arch).strip() #removes all types of white-space characters
or:
strarch = str(arch).rstrip('\n') #removes only trailing '\n'
And you can also use string formatting here:
strarch = str(arch).rstrip('\n')
info.write("{}: {} {}".format("Arch Bits", strarch, "bits"))
Note that there's no need of info.close()
, with
statement automatically closes the file for you.
Upvotes: 3