使用gspread读取谷歌表格触发UnicodeDecodeError故障求助
解决Python3.5.4中gspread读取Google Sheets的UnicodeDecodeError问题
首先,你遇到的问题根源在于Python3已经移除了sys.setdefaultencoding方法,所以第一种方法必然无效;而PYTHONIOENCODING是控制终端IO的编码,和gspread读取Sheets数据时的解码逻辑无关,因此第二种方法也起不到作用。下面给你几个可行的解决方案:
方案1:升级gspread到兼容Python3的版本
旧版本的gspread在Python3环境下处理非标准utf-8字符时可能存在bug,建议先升级到最新兼容版本:
pip install --upgrade gspread
升级后再尝试运行你的原代码,很多编码问题会被新版本修复。
方案2:手动处理数据编码,绕过get_all_records
如果升级后问题依然存在,可以放弃使用get_all_records,改用get_all_values手动获取数据并处理编码:
from __future__ import print_function import gspread from oauth2client.client import SignedJwtAssertionCredentials import pandas as pd import json SCOPE = ["https://spreadsheets.google.com/feeds"] SECRETS_FILE = "D:.......json" SPREADSHEET = "sheet" json_key = json.load(open(SECRETS_FILE)) credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], SCOPE) gc = gspread.authorize(credentials) workbook = gc.open(SPREADSHEET) sheet = workbook.sheet1 # 手动获取所有数据并处理编码 rows = sheet.get_all_values() headers = rows[0] # 第一行作为列名 processed_data = [] for row in rows[1:]: cleaned_row = [] for cell in row: # 尝试用latin-1转码修复utf-8解码错误,这是处理此类问题的常用技巧 try: cleaned_cell = cell.encode('latin-1').decode('utf-8') except UnicodeDecodeError: # 如果还是失败,保留原始内容或者替换为占位符 cleaned_cell = cell.replace(chr(0xd0), '') # 或者直接保留原内容 cleaned_row.append(cleaned_cell) processed_data.append(cleaned_row) # 构造DataFrame db = pd.DataFrame(processed_data, columns=headers) db.head()
这里的核心思路是:用latin-1编码先把字符转成字节,再用utf-8解码,能修复大部分因编码不兼容导致的错误。
方案3:检查并清理Google Sheets中的特殊字符
如果上述方法都无效,建议检查你的Google Sheets内容,是否存在一些非utf-8编码的特殊字符(比如某些旧系统生成的特殊符号),可以手动替换或删除这些字符后再尝试读取。
内容的提问来源于stack exchange,提问作者Edward
相关产品推荐
相关产品推荐

