通过使用上下文管理器,我的代码将文本以降序(第一行而不是第一行)写入文件

发布于 2025-01-21 01:46:18 字数 1183 浏览 1 评论 0原文

我正在尝试使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花落人断肠 2025-01-28 01:46:18

您可能想要 .flush() 您的文件 - 仅在“刷新”时,实际文件内容才会写入光盘 - 在此之前,文件对象会在其内部缓冲区中缓存需要完成的操作:

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') 
            self.file.flush()  ########## here ##########
            return self.file


        def __exit__(self, exception_type, exception_value, traceback):
            self.file.write(f'{self.indent*"  "}</{self.tag_name}>\n')
            self.file.close()

    # fixed indentation        
    def __init__(self):
        self.indent = -2

    # fixed indentation        
    def tag(self, tag_name):
        self.indent += 2        
        return self.HtmlTable(self.indent, tag_name)


def main():
    with open("test.html","w") as f:
        f.write("\n")

    doc = DOM()
    with doc.tag('html'):
        pass
        with doc.tag('head'):
            pass

    print(open("test.html").read())

if __name__ == '__main__':
    main()

== >

;
    <头>
    

目前,文件本身会在需要时将其缓冲区刷新到光盘 - 当您在 __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:

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') 
            self.file.flush()  ########## here ##########
            return self.file


        def __exit__(self, exception_type, exception_value, traceback):
            self.file.write(f'{self.indent*"  "}</{self.tag_name}>\n')
            self.file.close()

    # fixed indentation        
    def __init__(self):
        self.indent = -2

    # fixed indentation        
    def tag(self, tag_name):
        self.indent += 2        
        return self.HtmlTable(self.indent, tag_name)


def main():
    with open("test.html","w") as f:
        f.write("\n")

    doc = DOM()
    with doc.tag('html'):
        pass
        with doc.tag('head'):
            pass

    print(open("test.html").read())

if __name__ == '__main__':
    main()

==>

<html >
    <head >
    </head>
</html>

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文