You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python入门:如何将用户输入内容正确写入HTML文件?

问题分析与解决方案

你的代码核心问题是没有将用户输入的变量值插入到HTML字符串中,而是直接写了固定的name和content文本;同时定义了data模板但未实际写入文件,文件操作也不够规范。

修正后的代码(推荐使用f-string,直观简洁)

# 收集用户输入
name = input("请输入你的姓名: ")
content = input("请描述你自己: ")

# 使用with语句自动管理文件,无需手动关闭
with open("program6.html", "w", encoding="utf-8") as f:
    # 用f-string将变量嵌入HTML模板
    html_content = f'''
<html>
<head>
    <title>用户信息展示</title>
</head>
<body>
    <center>
        <h1>{name}</h1>
    </center>
    <hr />
    {content}
    <hr />
</body>
</html>'''
    f.write(html_content)

关键修改点说明

  1. 字符串格式化:在字符串前添加f前缀,把变量放在{}中,Python会自动将变量值替换到对应位置,替代原来的固定文本name、content。
  2. 文件操作优化:使用with open(...)语句,代码块结束后会自动关闭文件,避免手动close()可能引发的异常或遗漏。
  3. 编码设置:添加encoding="utf-8"确保生成的HTML文件支持中文等非ASCII字符(如果用户输入包含中文的话)。

另一种可选方案(使用str.format()方法)

如果习惯用占位符的方式,也可以这样写:

name = input("请输入你的姓名: ")
content = input("请描述你自己: ")

# 定义带占位符的HTML模板
html_template = '''
<html>
<head>
    <title>用户信息展示</title>
</head>
<body>
    <center>
        <h1>{user_name}</h1>
    </center>
    <hr />
    {user_content}
    <hr />
</body>
</html>'''

# 替换模板中的占位符
html_content = html_template.format(user_name=name, user_content=content)

with open("program6.html", "w", encoding="utf-8") as f:
    f.write(html_content)

内容的提问来源于stack exchange,提问作者Mariah C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:01:25