将Python字符串对象写入文件

将Python字符串对象写入文件,python,string,object,Python,String,Object,我有一段代码可以可靠地创建字符串对象。我需要把那个对象写入一个文件。我可以打印“数据”的内容,但我不知道如何将其作为输出写入文件。还有,为什么“打开”会自动关闭\u字符串 with open (template_file, "r") as a_string: data=a_string.read().replace('{SERVER_NAME}', server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}', conten

我有一段代码可以可靠地创建字符串对象。我需要把那个对象写入一个文件。我可以打印“数据”的内容,但我不知道如何将其作为输出写入文件。还有,为什么“打开”会自动关闭\u字符串

with open (template_file, "r") as a_string:
   data=a_string.read().replace('{SERVER_NAME}', server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}', content_path).replace('{DAMPATH}', dampath).replace('{ENV}', env).replace('{CACHE_DOCROOT}', cache_docroot)
我可以打印“数据”的内容,但我不知道如何将其作为输出写入文件

在打开时使用
,模式为“w”,并使用
写入
,而不是
读取

with open(template_file, "w") as a_file:
   a_file.write(data)
还有,为什么“打开”会自动关闭\u字符串

with open (template_file, "r") as a_string:
   data=a_string.read().replace('{SERVER_NAME}', server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}', content_path).replace('{DAMPATH}', dampath).replace('{ENV}', env).replace('{CACHE_DOCROOT}', cache_docroot)
open
返回一个
文件
对象,该对象实现了
\uuuuuuuuuuuuuu进入
\uuuuuuu退出
方法。当您使用
块输入
时,将调用
\uuuu enter\uuuu
方法(打开文件),当使用
块退出时,将调用
\uu exit\uuu
方法(关闭文件)

您可以自己实现相同的行为:

class MyClass:
    def __enter__(self):
        print 'enter'
        return self

    def __exit__(self, type, value, traceback):
        print 'exit'

    def a(self):
        print 'a'

with MyClass() as my_class_obj:
     my_class_obj.a()
上述代码的输出将为:

'enter'
'a'
'exit'

a\u string.write(您的\u string\u对象)
应该可以在
中使用
块写入字符串到文件中,还是读取文件并替换部分读取字符串?我需要将模板文件读入内存,对其进行更改,然后将(更改的)对象写入新文件中。我不想“就地”编辑文件。我昨天学习了链接,今天学习了字符串格式。我不知道是否应该关闭该文件,但我的目标是能够生成一个配置文件,并一次性命名它。