UnicodeEncodeError: 在写入HTML时,'charmap' 编解码器无法对字符进行编码

前端开发 2026-07-11

我有一个pandas DataFrame,想把它粘贴到一个HTML文档中。这个 DataFrame 包含用作符号的Dingbat字符,用以突出显示值:良好(勾号)、几乎不佳(三角形),或差(感叹号)。下面是相关的代码片段:

df.loc[0, 0] = '\u2705'
html = df.to_html(justify='center')

随后我使用下面的函数将HTML字符串 html 插入到我的模板HTML文件中:

def injectHTML(obj_to_insert, dest_file_path, start_string):
    for line in fileinput.FileInput(dest_file_path, inplace=1):
        if start_string in line:
            line = line.replace(line,line+obj_to_insert)
        print (line, end=" ")

运行整段代码时,出现以下错误:

Traceback (most recent call last):

  File ~\AppData\Local\anaconda3\Lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File c:\users\m324461\documents\github\my_app\sandbox.py:956
    createReport()

  File c:\users\m324461\documents\github\my_app\sandbox.py:851 in createReport
    injectHTML(html, foutname, "#_Table")

  File c:\users\m324461\documents\github\my_app\sandbox.py:151 in injectHTML
    print (line, end=" ")

  File ~\AppData\Local\anaconda3\Lib\encodings\cp1252.py:19 in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]

UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 723: character maps to <undefined>

我尝试更改编码:

print (line.encode("utf-8", end=" ")

这在执行时没有报错,但输出变得完全不可读取。

我也尝试用ASCII编码,但得到不同的错误:

UnicodeEncodeError: 'ascii' codec can't encode character '\u2705' in position 696: ordinal not in range(128)

我使用的是Python 3.11.5和 pandas 2.0.3。

我到底哪里做错了?


更新2026-03-20

我将 injectHTML() 函数改为如下(基于一个现在已经消失、原因不明的回答):

def injectHTML(obj_to_insert, dest_file_path, start_string):
    with open(dest_file_path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    with open(dest_file_path, "w", encoding="utf-8") as f:
        for line in lines:
            if start_string in line:
                line = line + obj_to_insert
            f.write(line)

现在代码可以执行,但写入的是错误的字符。用Chrome或 Edge查看时,我得到的是 ✅,而不是

我尝试在同一个会话中执行我的代码之前,在Windows 11的命令行中运行 chcp 65001,但这并没有帮助。

如果我在Notepad++打开该文件,字符是正确的。

解决方案

为后事着想,我将为这个问题的评论总结一个回答。

第一个问题通过将 InjectHTML 函数更新为使用内置的WRITE函数来替代向 stdout 打印解决:

# Source - https://stackoverflow.com/q/79909353
# Posted by Kes Perron, modified by community. See post 'Timeline' for change history
# Retrieved 2026-03-23, License - CC BY-SA 4.0

def injectHTML(obj_to_insert, dest_file_path, start_string):
    with open(dest_file_path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    with open(dest_file_path, "w", encoding="utf-8") as f:
        for line in lines:
            if start_string in line:
                line = line + obj_to_insert
            f.write(line)

接着,在整个脚本运行之前,在批处理文件中添加了 chcp 65001,以便Windows CMD会话使用正确的编码。

最后,在模板HTML文件中添加了 <meta charset="UTF-8">,以便浏览器使用正确的解码。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章