我在这里有一个简单的bash命令用于我用Python重写的脚本,我做了很多搜索,但没有找到一个简单的答案。我试图将Print的输出回显到文件,确保没有换行符,并且我可以将变量传递给它。这里只是一个小片段(有很多这样的行):
echo " ServerName www.${hostName}" >> $prjFile
现在我知道它最终会看起来像:
print ("ServerName www.", hostName) >> prjFile
右?但这不起作用。请注意,这是在Python 2.6中(因为此脚本将运行的机器正在使用该版本,并且还有其他依赖项依赖于该版本)。
答案 0 :(得分:8)
语法是;
print >>myfile, "ServerName www.", hostName,
其中myfile是以模式"a"
打开的文件对象(用于“追加”)。
尾随逗号可防止换行。
您可能还希望使用sys.stdout.softspace = False
来阻止Python在逗号分隔的参数之间添加print
的空格,和/或将事物打印为单个字符串:
print >>myfile, "ServerName www.%s" % hostName,
答案 1 :(得分:4)
你可以尝试一个简单的:
myFile = open('/tmp/result.file', 'w') # or 'a' to add text instead of truncate
myFile.write('whatever')
myFile.close()
在你的情况下:
myFile = open(prjFile, 'a') # 'a' because you want to add to the existing file
myFile.write('ServerName www.{hostname}'.format(hostname=hostname))
myFile.close()