无需本地下载读取Google Drive Excel至DataFrame时遇配置错误
问题:读取Google Drive Excel文件到DataFrame时触发InvalidConfigError错误
尝试直接读取Google Drive中的Excel文件到DataFrame,代码如下:
credentialFileOfServiceAccount = 'x.json' scope = ['https://www.googleapis.com/auth/drive'] #edited by ashraf creds = ServiceAccountCredentials.from_json_keyfile_name(credentialFileOfServiceAccount, scope) print(creds) spreadsheetId=file.get("id") gauth = GoogleAuth() gauth.LocalWebserverAuth() url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media" res = requests.get(url, headers={"Authorization": "Bearer " + gauth.attr[creds].access_token}) # 2. The downloaded XLSX data is read with `pd.read_excel`. sheet = "Sheet1" values = pd.read_excel(BytesIO(res.content), usecols=None, sheet_name=sheet) print(values)
运行时出现错误:
InvalidConfigError: Invalid client secrets file ('Error opening file', 'client_secrets.json', 'No such file or directory', 2)
排查与解决方法
核心问题:混用两种认证方式
你的代码同时使用了服务账号认证(ServiceAccountCredentials)和本地网页授权(GoogleAuth),而gauth.LocalWebserverAuth()默认会在当前目录查找client_secrets.json文件(OAuth客户端凭证),但你只提供了服务账号的x.json,导致文件找不到错误。
解决步骤
方案1:统一使用服务账号认证(推荐)
既然已经准备了服务账号凭证,直接用它完成全部认证流程,无需再调用GoogleAuth:
from oauth2client.service_account import ServiceAccountCredentials import requests import pandas as pd from io import BytesIO # 服务账号凭证文件路径 credentialFileOfServiceAccount = 'x.json' scope = ['https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name(credentialFileOfServiceAccount, scope) # 获取访问令牌 access_token = creds.get_access_token().access_token # 替换为你的目标文件ID file_id = "你的Google Drive文件ID" url = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media" # 请求文件内容 res = requests.get(url, headers={"Authorization": f"Bearer {access_token}"}) # 读取Excel到DataFrame sheet = "Sheet1" values = pd.read_excel(BytesIO(res.content), usecols=None, sheet_name=sheet) print(values)
额外注意事项:
- 打开
x.json找到client_email字段,将该邮箱地址添加为目标Excel文件的共享用户(赋予查看权限) - 确保服务账号已在Google Cloud Console中启用Drive API
方案2:改用本地网页授权(GoogleAuth)
如果坚持使用本地网页授权,需要:
- 从Google Cloud Console的「OAuth 2.0客户端ID」页面下载
client_secrets.json文件,放在代码同目录下 - 移除服务账号相关代码,调整为以下逻辑:
from pydrive.auth import GoogleAuth import requests import pandas as pd from io import BytesIO gauth = GoogleAuth() gauth.LocalWebserverAuth() # 此时会自动读取client_secrets.json file_id = "你的Google Drive文件ID" url = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media" res = requests.get(url, headers={"Authorization": f"Bearer {gauth.attr['credentials'].access_token}"}) sheet = "Sheet1" values = pd.read_excel(BytesIO(res.content), usecols=None, sheet_name=sheet) print(values)
内容的提问来源于stack exchange,提问作者Mohamed Ashraf
相关产品推荐
相关产品推荐

