【发布时间】:2020-11-24 06:04:13
【问题描述】:
我正在尝试使用 Python 访问和修改 Google 电子表格上的数据。我无法从 Python 打开 Google 电子表格。在编写任何代码之前,我密切关注各种教程并准备了以下内容。
- 在 GCP Console 上启用 Google Sheets API 和 Google Drive API
- 从 GCP Console 生成和下载的凭据(JSON 文件)
- 电子表格:与 JSON 文件中的客户电子邮件共享(编辑访问)
- 已安装 gspread 和 oauth2client -->
pip install gspread oauth2client
以下是与 Google 表格交互的 Python 代码。第 12 行和第 13 行的目标是将链接的 Google 电子表格中的所有数据输出到控制台。
1 import gspread
2 from oauth2client.service_account import ServiceAccountCredentials
3
4 scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
5 creds = ServiceAccountCredentials.from_json_keyfile_name('Py-Sheets.json', scope)
6 client = gspread.authorize(creds)
7
8 print("Hello World")
9
10 sheet = client.open("Test-Sheets").sheet1
11
12 sample = sheet.get_all_records()
13 print(sample)
直到第 10 行(上图),一切似乎都运行良好,我收到一条错误消息 SpreadsheetNotFound。这是完整的错误(如下)。
Traceback (most recent call last):
File "/home/username/anaconda3/lib/python3.7/site-packages/gspread/client.py", line 119, in open
self.list_spreadsheet_files(title),
File "/home/username/anaconda3/lib/python3.7/site-packages/gspread/utils.py", line 97, in finditem
return next((item for item in seq if func(item)))
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pysheets.py", line 10, in <module>
sheet = client.open("Test-Sheets").sheet1
File "/home/username/anaconda3/lib/python3.7/site-packages/gspread/client.py", line 127, in open
raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound
我还通过电子邮件收到以下错误。
DNS Error: 15698833 DNS type 'mx' lookup of python-spreadsheets-123456.iam.gserviceaccount.com responded with code NXDOMAIN Domain name not found: python-spreadsheets-123456.iam.gserviceaccount.com
如何修复执行第 10 行后产生的错误?该代码与我在教程中找到的代码几乎完全相同。电子表格的名称与我在client.open() 中输入的完全一致。电子表格是否必须位于特定的 GDrive 目录中才能找到?
【问题讨论】:
-
该文件不应位于特定的云端硬盘文件夹中,因此要么您实际上并未与服务帐户共享该文件,要么电子表格名称中存在拼写错误。我建议你仔细检查一下。
标签: python google-sheets