How to export DataFrame to Html with utf-8 encoding?

后端 未结 4 1459
南笙
南笙 2021-01-05 05:39

I keep getting:

UnicodeEncodeError: \'ascii\' codec can\'t encode characters in position 265-266: ordinal not in range(128)

when I try:

4条回答
  •  无人及你
    2021-01-05 06:22

    The issue is actually in using df.to_html("mypage.html") to save the HTML to a file directly. If instead you write the file yourself, you can avoid this encoding bug with pandas.

    html = df.to_html()
    with open("mypage.html", "w", encoding="utf-8") as file:
        file.write(html)
    

    You may also need to specify the character set in the head of the HTML for it to show up properly on certain browsers (HTML5 has UTF-8 as default):

    This was the only method that worked for me out of the several I've seen.

提交回复
热议问题