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

用户输入Excel路径后用Pandas读取遇UnicodeDecodeError,求解决

解决pd.ExcelFile读取文件时的UnicodeDecodeError问题

你的问题出在用文本模式打开了二进制格式的Excel文件。Excel文件(.xls/.xlsx)本质是二进制文件,而你用'r+'文本模式打开时,Python会尝试用系统默认编码(这里是cp1252)去解码文件内容,可Excel文件里的二进制字节并不符合这个编码规则,所以就抛出了UnicodeDecodeError。

修复方案1:用二进制模式打开文件

把打开文件的模式改成'rb'(只读二进制模式),这样就不会触发编码解码操作,直接传递二进制内容给pandas:

import sys
import os
import pandas as pd

user_input = input("Enter the path of your file: ")
assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
# 用二进制模式打开文件
f = open(user_input,'rb')
xl = pd.ExcelFile(f)
# 记得用完文件后手动关闭
f.close()

修复方案2:更简洁的写法(推荐)

其实pandas的pd.ExcelFile可以直接接收文件路径字符串,不需要手动打开文件——pandas会自动处理文件的打开、读取和关闭操作,代码更简洁也更安全:

import os
import pandas as pd

user_input = input("Enter the path of your file: ")
assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
# 直接将文件路径传给pd.ExcelFile
xl = pd.ExcelFile(user_input)

这样既避免了手动打开文件带来的编码问题,也省去了手动关闭文件的步骤,减少了资源泄漏的风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:45:20