[英]write Python string object to file
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”会自动关闭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
与模式“w”和write
的,而不是read
:
with open(template_file, "w") as a_file:
a_file.write(data)
Also why does "with open" automatically close a_string?
另外,为什么“ with open”会自动关闭a_string?
open
returns a File
object, which implemented both __enter__
and __exit__
methods. open
返回一个File
对象,该对象同时实现了__enter__
和__exit__
方法。 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). 当您输入
with
块时,将__enter__
方法(将打开文件),而当退出with
块时,将调用__exit__
方法(将关闭文件)。
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'
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).replace('{SLD}', sld)
filename = "{NNN}_{BRAND}_farm.any".format(BRAND=brand, NNN=nnn)
with open(filename, "w") as outstream:
outstream.write(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.