在python中使用gspread import_csv函数时找不到文件

问题描述 投票:0回答:1

我在python中使用gspread包。

我尝试将csv导入谷歌电子表格但我收到了一个错误。

我的代码如下:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

spreadsheet_id = '1tFhK2-zebkG1fZFF6Xe5LHyONkh97ANOkcf'

scopes = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]

creds = ServiceAccountCredentials.from_json_keyfile_name('./credentials.json', scopes=scopes)

client = gspread.authorize(creds)

file = open('test_csv.csv',mode='r')
csv = file.read()
file.close()

client.import_csv(spreadsheet_id, csv)

我得到的错误是:

---------------------------------------------------------------------------
APIError                                  Traceback (most recent call last)
<ipython-input-264-eb5d4ce7bc69> in <module>()
----> 1 client.import_csv(spreadsheet_id, csv)

~/anaconda3/lib/python3.6/site-packages/gspread/client.py in import_csv(self, file_id, data)
    238                 'convert': True
    239             },
--> 240             headers=headers
    241         )
    242 

~/anaconda3/lib/python3.6/site-packages/gspread/client.py in request(self, method, endpoint, params, data, json, files, headers)
     77             return response
     78         else:
---> 79             raise APIError(response)
     80 
     81     def list_spreadsheet_files(self):

APIError: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "File not found: 1tFhK2-zebkG1fZFF6Xe5LHyONkh97ANOkcf",
    "locationType": "other",
    "location": "file"
   }
  ],
  "code": 404,
  "message": "File not found: 1tFhK2-zebkG1fZFF6Xe5LHyONkh97ANOkcf"
 }
}

但是,当我尝试直接读取或写入单元格时(例如使用update_cell函数),我没有错误,因此电子表格确实存在,我可以在上面写。特别是import_csv抛出错误。

我通过谷歌驱动器网络界面创建了谷歌表。然后,我将来自credential.json([email protected])的client_email添加到电子表格的授权邮件中。

有什么建议吗?

python google-api gspread
1个回答
0
投票

我通过在凭证JSON文件中找到的'client_email'共享文件来修复它。虽然我没有对此进行测试,但我也怀疑将电子表格公开(Web上的任何人都可以看到)将解决问题。

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.