簡體   English   中英

在python中使用gspread import_csv函數時找不到文件

[英]File not found when using gspread import_csv function in python

我在 python 中使用 gspread 包。

我嘗試將 csv 導入 Google 電子表格,但出現錯誤。

我的代碼如下:

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 (blabla@blabla-220209.iam.gserviceaccount.com) 的 client_email。

有什么建議嗎?

我通過與憑證 JSON 文件中的“client_email”共享文件來修復它。 雖然我沒有對此進行測試,但我也懷疑將電子表格設為公開(網絡上的任何人都可以看到)將解決該問題。

干杯!

通過轉到您的工作表並將共享選項更改為具有鏈接的任何人都可以編輯,修復它。

這是我使用的代碼:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ["(some scopes)"]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
gc = gspread.service_account("creds.json", scope)
client = gspread.authorize(creds)
sLink = "(link)"
sh = gc.open_by_url(sLink)
sh.share('<example.email.com>', perm_type='user', role='writer')

確保您使用的是最新版本的 gspread。 例如,與 Google Colab 捆綁在一起的那個已經過時了:

!pip install --upgrade gspread

這為我修復了gs.csv_import的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM