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

Python多行字符串格式化报错(KeyError):生成全年每日HTML文件时的问题

解决Python生成每日HTML文件时的KeyError问题

你在尝试为全年每一天生成HTML文件,用str.format()替换模板里的day、month和bg参数时,遇到了这个报错:

Traceback (most recent call last):
  File "c:\Users\Galax\Dokumente\Programming\Python\GenerateBirthdayCounters\main.py", line 23, in <module>
    make_file(str(month),str(day))
  File "c:\Users\Galax\Dokumente\Programming\Python\GenerateBirthdayCounters\main.py", line 9, in make_file
    f.write(html.format(day=day.rjust(2, "0"),month=month.rjust(2, "0"),bg="#660066"))
KeyError: '\n --smaller'

问题原因

这个报错的核心是:你的HTML模板里存在未转义的单花括号(比如{--smaller}这类内容),而Python的str.format()方法会把所有单花括号包裹的内容都当作需要替换的占位符。你只提供了day、month、bg三个参数,模板里其他的花括号没有对应的参数,所以就触发了KeyError。

解决方案

把HTML模板中不需要作为替换变量的单花括号全部改成双花括号{{}},这样format()方法就会将它们解析成普通的单花括号字符,而不是占位符。

比如模板里的:

{--smaller}

修改后变成:

{{--smaller}}

把所有类似的非变量花括号都做这样的替换,就能解决这个报错。

额外优化:简化月份天数判断

你代码里手动判断每个月天数的逻辑存在小错误(比如4、6、9、11月是30天,但当前逻辑会给这些月份生成31天的文件)。可以用Python内置的calendar模块来自动获取每个月的天数,代码更简洁准确:

import os
import calendar
from html import html

os.mkdir("pages")
os.chdir("pages")

def make_file(month, day):
    with open(f"{day}.html", "w") as f:
        f.write(html.format(day=day.rjust(2, "0"),month=month.rjust(2, "0"),bg="#660066"))

for month in range(1,13):
    os.mkdir(str(month))
    os.chdir(str(month))
    # 获取当前月份的天数,自动处理平闰年的2月
    _, num_days = calendar.monthrange(2024, month)
    for day in range(1, num_days + 1):
        make_file(str(month), str(day))
    os.chdir("..")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:42:32