通过使用上下文管理器,我的代码将文本以降序(第一行而不是第一行)写入文件
我正在尝试使用Python中的类编写HTML。我的讲师已经提供了一些指导。当我尝试与函数一起使用将文本写入HTML文件时,首先将第一个启动的行写入文件中。我可以知道如何解决吗?
代码:
class DOM:
class HtmlTable:
def __init__(self, indent, tag_name):
self.indent = indent
self.tag_name = tag_name
def __enter__(self):
self.file = open('test.html', 'a')
self.file.write(f'{self.indent*" "}<{self.tag_name} >\n')
return self.file
def __exit__(self, exception_type, exception_value, traceback):
self.file.write(f'{self.indent*" "}</{self.tag_name}>\n')
self.file.close()
def __init__(self):
self.indent = -2
def tag(self, tag_name):
self.indent += 2
return self.HtmlTable(self.indent, tag_name)
测试:
if __name__ == '__main__':
doc = DOM()
with doc.tag('html'):
with doc.tag('head'):
#remaining code
输出:
<head >
</head>
<html >
</html>
所需的输出:
<html >
<head >
</head>
</html>
I am trying to write html using class in Python. Some guidance have been given by my lecturer. When I try to use with function to write text into the HTML file, the lines below the first initiation are written into the file first. Can I know how to solve it?
Code:
class DOM:
class HtmlTable:
def __init__(self, indent, tag_name):
self.indent = indent
self.tag_name = tag_name
def __enter__(self):
self.file = open('test.html', 'a')
self.file.write(f'{self.indent*" "}<{self.tag_name} >\n')
return self.file
def __exit__(self, exception_type, exception_value, traceback):
self.file.write(f'{self.indent*" "}</{self.tag_name}>\n')
self.file.close()
def __init__(self):
self.indent = -2
def tag(self, tag_name):
self.indent += 2
return self.HtmlTable(self.indent, tag_name)
Test:
if __name__ == '__main__':
doc = DOM()
with doc.tag('html'):
with doc.tag('head'):
#remaining code
Output:
<head >
</head>
<html >
</html>
Desired Output:
<html >
<head >
</head>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想要
.flush()
您的文件 - 仅在“刷新”时,实际文件内容才会写入光盘 - 在此之前,文件对象会在其内部缓冲区中缓存需要完成的操作:== >
目前,文件本身会在需要时将其缓冲区刷新到光盘 - 当您在
__exit__()
中点击self.file.close()
时,它“是需要的”。第一个__exit__
是针对标签"head"
完成的。在文件被“刷新”之前,“要写入的内容”将保留在文件对象内部缓冲区中 - 这就是您获得输出的原因。
You may want to
.flush()
your file - only on "flush" the actual file content is written to disc - until then the file object caches what needs to be done in its internal buffer:==>
Currently the file itself flushes its buffer to disc when needed - it "is needed" when you hit
self.file.close()
in your__exit__()
. The first__exit__
is done for the tag"head"
.Until the file is "flushed" the "things to be written" are kept in the file objects internal buffer - that is the reason for the output you are getting.