Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 授权Google Drive服务帐户将数据写入Google Sheets_Python_Google Colaboratory - Fatal编程技术网

Python 授权Google Drive服务帐户将数据写入Google Sheets

Python 授权Google Drive服务帐户将数据写入Google Sheets,python,google-colaboratory,Python,Google Colaboratory,我正在使用Google Co.lab笔记本在我的个人Google Drive帐户中的Google工作表上写一个pandasdataframe 我用Google Drive API创建了一个服务帐户,并创建了一个API密钥,该密钥位于Google Drive中(My Drive/project/scrapers/utils/auth_key.json)。我想通过驱动器服务进行身份验证,以便根据使用驱动器API将工作表移动/写入特定文件夹 我对服务帐户的身份验证有问题: import os impo

我正在使用Google Co.lab笔记本在我的个人Google Drive帐户中的Google工作表上写一个
pandas
dataframe

我用Google Drive API创建了一个服务帐户,并创建了一个API密钥,该密钥位于Google Drive中(
My Drive/project/scrapers/utils/auth_key.json
)。我想通过驱动器服务进行身份验证,以便根据使用驱动器API将工作表移动/写入特定文件夹

我对服务帐户的身份验证有问题:

import os
import gspread

# Mount Google Drive

from google.colab import drive
drive.mount("/content/gdrive")

# Authenticate service account

from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
filepath = os.path.expanduser('/content/gdrive/My Drive/project/utils/api/service_key.json')
credentials = ServiceAccountCredentials.from_json_keyfile_name(filepath, scope)
gc = gspread.authorize(credentials)

# Specify spreadsheet name and desired folder

title = 'test'  # Spreadsheet name.
my_path = "/project/scrapers/csv_output" # File path
destFolderId = "/content/gdrive" + "/My Drive" + my_path # Full file path

# Write spreadsheet to desired folder

from apiclient import discovery

drive_service = discovery.build('drive', 'v3', credentials=credentials)
file_metadata = {
    'name': title,
    'mimeType': 'application/vnd.google-apps.spreadsheet',
    'parents': [destFolderId]
}
file = drive_service.files().create(body=file_metadata).execute()
一旦装载完成,这将导致错误

drive.mount('/content/gdrive')
文件的访问方式如下

/content/gdrive/My Drive/Test_Data/elephant.jpg
为了


验证API及其作用域。

从google drive访问文件是否也会引发错误?装载完成后
drive.mount('/content/gdrive')
。可以像
'/content/gdrive/My Drive/Test_Data/elephant.jpg'
@simpleApp一样访问该文件。我能够装载该驱动器,并且建议的文件路径有效!我现在遇到另一个错误,即
权限不足:请求的身份验证范围不足。
我认为这可能与我的服务帐户的权限有关,因此我已更新了我的问题,并将继续研究该问题。非常感谢。我想是的,api键和作用域不匹配。另外,请粘贴完整的跟踪日志,因为这会有所帮助。@simpleApp你是对的-我更改了范围,查询成功了。我发现的下一个问题是,当我需要一个文件夹ID时,我正在传递一个文件路径。你知道这个用例的最佳实践是什么吗?我应该删除我的问题吗?我想它可以作为将来的参考。让我过滤这些评论并给出答案。
ServiceAccountCredentials.from_json_keyfile_name(filepath, scope)