我正在嘗試使用 Python 中的類撰寫 html。我的講師已經給出了一些指導。當我嘗試使用 with 函式將文本寫入 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>
uj5u.com熱心網友回復:
您可能希望.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()
==>
<html > <head > </head> </html>
目前,檔案本身會在需要時將其緩沖區重繪 到磁盤 - 當您self.file.close()點擊__exit__(). 第一個__exit__是為標簽完成的"head"。
在檔案被“重繪 ”之前,“要寫入的東西”被保存在檔案物件內部緩沖區中——這就是你得到輸出的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458923.html
上一篇:替換文本檔案Python中的值
