在不导入 os 的情况下通过 Python 写入 HTML? (Python 3.8 / Windows)

Writing to HTML through Python without import os? (Python 3.8 / Windows)

基本上,我想知道的是,是否有一种不需要 import os 模块的更简单的编写方法? 我想使用 HTML 文件从 Python 创建一个简单的网页。虽然这正是我想要的,但我似乎无法想出一种 simple/basic 方式,或者一种不涉及 import os 模块的方式。

import os

name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")

with open('mypage.html', 'rt') as file:
    with open('temp_mypage.html', 'wt') as new:
        for line in file:
            line = line.replace('some_name', name)
            line = line.replace('some_persona', persona)
            new.write(line)

os.remove('mypage.html')
os.rename('temp_mypage.html', 'mypage.html')

HTML代码:

<html>
<head>
<body>
<center>
<h1>
some_name
# input into the file
</h1>
</center>
<hr />
some_persona
<hr />
</body>
</html>

你不需要os模块和临时文件,相反你可以只添加到一个变量并写回

name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")
new = ""

with open('mypage.html', 'rt') as file:
        for line in file:
            line = line.replace('some_name', name)
            line = line.replace('some_persona', persona)
            new += line.strip()

with open('mypage.html','w') as f:
        f.write(new)

对于像这样的任务,不推荐使用这种方法。使用像 Flask 这样的 Web 框架(对于这个简单的框架,Django 将是头等大事),CGI 脚本现在已经过时了