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

Python Pandas导出UTF-8 CSV时特殊字符乱码问题求助

问题描述

以网页https://www.basketball-reference.com/draft/NBA_2018.html为例,该网页编码为UTF-8。执行以下代码提取页面表格:

html = requests.get("https://www.basketball-reference.com/draft/NBA_2018.html", headers={"User-Agent": "XY"}).content
df_list = pandas.read_html(html)

控制台中df_list[0]可正确显示第三顺位球员名字为Dončić,但执行CSV导出代码时:

with open('C:/Users/Eric/br2.csv', 'a', encoding='utf-8') as f:
 df_list[0].to_csv(f, header=True, encoding='utf-8')

名字显示为DonÄić。尝试多种编码方案均未解决:

  • 使用utf-8-sig编码仍出现乱码
  • 使用latin1编码或不指定编码无法正常打开文件
  • 直接打印DataFrame内容,同样显示DonÄić
  • 改用requests.get().text提取内容,结果变为DonÄÂić

补充测试发现:

  • Excel或Notepad以UTF-8编码打开生成的CSV仍乱码,但Open Office以UTF-8打开显示正常
  • 将Luka Dončić复制到Notepad并保存为新CSV后,Excel和Notepad以UTF-8打开均显示正常
    推测问题出在pandas的to_csv函数生成的CSV编码处理上。
解决方案

推荐采用以下方法解决编码问题:

  • 避免双重编码操作:不要同时在open()和to_csv()中指定编码,直接调用to_csv()并指定utf-8-sig编码(自动添加BOM头,适配Excel的UTF-8识别逻辑):
df_list[0].to_csv('C:/Users/Eric/br2.csv', mode='a', header=True, encoding='utf-8-sig')
  • 手动转换编码后写入:若上述方法无效,可先将DataFrame转换为UTF-8编码的CSV字符串,再写入文件:
csv_content = df_list[0].to_csv(header=True, encoding='utf-8')
with open('C:/Users/Eric/br2.csv', 'a', encoding='utf-8') as f:
    f.write(csv_content)
  • 统一字符串编码:对DataFrame中的字符串进行编码转换,确保内容为标准UTF-8后再导出:
df = df_list[0].applymap(lambda x: x.encode('utf-8').decode('utf-8') if isinstance(x, str) else x)
df.to_csv('C:/Users/Eric/br2.csv', mode='a', header=True, encoding='utf-8-sig')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:25:10