Python:回应文件(如Bash)

问题描述 投票:2回答:2

我在这里有一个简单的bash命令,用于我用Python重写的脚本,我做了很多搜索,但没有找到一个简单的答案。我试图将Print的输出回显到文件,确保没有换行符,并且我可以将变量传递给它。这里只是一个小片段(有很多这样的行):

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

现在我知道它最终会看起来像:

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

对?但这不起作用。请注意,这是在Python 2.6中(因为此脚本将运行的机器正在使用该版本,并且还有其他依赖项依赖于该版本)。

python bash echo output
2个回答
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()

8
投票

语法是;

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

其中myfile是以模式"a"打开的文件对象(用于“追加”)。

尾随逗号可防止换行。

您可能还希望使用sys.stdout.softspace = False来阻止Python在逗号分隔的print参数之间添加的空格,和/或将事物打印为单个字符串:

print >>myfile, "ServerName www.%s" % hostName,
© www.soinside.com 2019 - 2024. All rights reserved.