2

I have a simple bash command here for a script that I am re-writing in Python, and I've done a lot of searching and haven't found a simple answer. I am trying to echo the output of Print to a file, making sure there are no line breaks and that I can pass a variable into it. Here is just a little snippet (there are a lot of lines like this):

echo "    ServerName  www.${hostName}" >> $prjFile

Now I know it would end up looking something like:

print ("ServerName www.", hostName) >> prjFile

Right? But that doesn't work. Mind you, this is in Python 2.6 (as the machine this script will run on is using that version and there are other dependencies reliant on sticking with that version).

2 Answers 2

7

The syntax is;

print >>myfile, "ServerName www.", hostName,

where myfile is a file object opened in mode "a" (for "append").

The trailing comma prevents line breaks.

You might also want to use sys.stdout.softspace = False to prevent the spaces that Python adds between comma-separate arguments to print, and/or to print things as a single string:

print >>myfile, "ServerName www.%s" % hostName,
Sign up to request clarification or add additional context in comments.

Comments

4

You can try a simple:

myFile = open('/tmp/result.file', 'w') # or 'a' to add text instead of truncate
myFile.write('whatever')
myFile.close()

In your case:

myFile = open(prjFile, 'a') # 'a' because you want to add to the existing file
myFile.write('ServerName www.{hostname}'.format(hostname=hostname))
myFile.close()

6 Comments

Note that file.write() doesn't add newlines.
The { } are just bashes way of pushing the variable in, ultimately the variable hostName is going to just be www.hostName.com or whatever.
I added it on @mgilson suggestion to make it possible to concatenate the variable.
The $ seems to be wrong, I am getting a syntax error. Would that be %? Nevermind I got it :) Thank you
To expand on @IgnacioVazquez-Abrams' comment echo appends a newline to it's contents, while python's fp.write() method does not. If you want to replicate an echo with write, be sure to add a newline to the end.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.