将 Python 字符串对象写入文件 [英] write Python string object to file

查看:127
本文介绍了将 Python 字符串对象写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以可靠地创建一个字符串对象.我需要将该对象写入文件.我可以打印数据"的内容,但我不知道如何将它作为输出写入文件.还有为什么with open"会自动关闭a_string?

 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}',damath).replace('{ENV}', env).replace('{CACHE_DOCROOT}', cache_docroot)

解决方案

<块引用>

我可以打印数据"的内容,但我不知道如何将其作为输出写入文件

使用 with open 和模式 'w' 和 write 而不是 read:

 with open(template_file, "w") as a_file:a_file.write(data)

<块引用><块引用>

还有为什么with open"会自动关闭a_string?

open 返回一个 File 对象,该对象实现了 __enter____exit__ 方法.当您进入 with 块时,__enter__ 方法被调用(打开文件),当 with 块退出时,__exit__ 方法被调用(关闭文件).

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

class MyClass:def __enter__(self):打印输入"回归自我def __exit__(self, type, value, traceback):打印退出"定义一个(自我):打印 'a'使用 MyClass() 作为 my_class_obj:my_class_obj.a()

以上代码的输出将是:

'回车''一种''出口'

I have this block of code that reliably creates a string object. I need to write that object to a file. I can print the contents of 'data' but I can't figure out how to write it to a file as output. Also why does "with open" automatically close a_string?

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)

解决方案

I can print the contents of 'data' but I can't figure out how to write it to a file as output

Use with open with mode 'w' and write instead of read:

with open(template_file, "w") as a_file:
   a_file.write(data)

Also why does "with open" automatically close a_string?

open returns a File object, which implemented both __enter__ and __exit__ methods. When you enter the with block the __enter__ method is called (which opens the file) and when the with block is exited the __exit__ method is called (which closes the file).

You can implement the same behavior yourself:

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()

The output of the above code will be:

'enter'
'a'
'exit'

这篇关于将 Python 字符串对象写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆