【问题标题】:credential JSON file to google colab凭证 JSON 文件到谷歌 colab
【发布时间】:2021-04-23 14:57:43
【问题描述】:

我正在尝试将 Python Jupyter 刮板脚本(和 json cred 文件)从我的笔记本电脑移动到 Google Colab。 我已经在 Google Colab 和 Google Drive 之间建立了连接。 我已将 (.ipynb) 脚本和凭据 JSON 文件存储在 Google Drive 上。 但是我无法在 2(gdrive json cred 文件和 colab)之间建立连接以使其工作。 下面是有关凭据处理的脚本部分:

# Sheet key
# 1i1bmMt-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_d7Eo

import gspread
import pandas as pd
import requests
from bs4 import BeautifulSoup
from oauth2client.service_account import ServiceAccountCredentials

# Access credentials for google sheet and access the google sheet
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"]

# Copy your path to your credential JSON file.
PATH_TO_CREDENTIAL = '/Users/user/json-keys/client_secret.json'

# Initiate your credential
credentials = ServiceAccountCredentials.from_json_keyfile_name(PATH_TO_CREDENTIAL, scope)

# Authorize your connection to your google sheet
gc = gspread.authorize(credentials)

我收到 FileNotFoundError: 和凭据错误 希望有人能帮帮我,谢谢

【问题讨论】:

    标签: python google-sheets google-drive-api google-colaboratory google-codelab


    【解决方案1】:

    您尝试将文件放在同一目录中以首先对其进行测试。确保文件没问题,可以成功运行。

    以下是源代码供参考:

    如果 client_secret.json 与您正在运行的文件位于同一目录中,则正确的语法是:

    import os
    DIRNAME = os.path.dirname(__file__)
    credentials = ServiceAccountCredentials.from_json_keyfile_name(os.path.join(DIRNAME, 'client_secret.json'), scope)
    

    如果上面的测试没问题,那么尝试将文件移动到你的目标目录'/Users/user/json-keys/client_secret.json',并尝试在当前目录中创建一个符号链接来链接client_secret。 json 文件。然后,用上面的代码运行程序再次测试。确保将文件放入该目录时没有问题。这是一种解决方法。

    我用这个案例作为参考: Django not recognizing or seeing JSON file

    【讨论】:

    • 谢谢。 .ipynb 和 .json 都在 gdrive 上的同一个“Colab Notebooks”文件中。当我使用您的语法时,我在“---> 18 DIRNAME = os.path.dirname(file) 上收到“NameError: name 'file' is not defined” ”。我需要指定文件夹或文件吗?
    • 您可以查看此案例:stackoverflow.com/questions/16771894/… 有多种方法可以修复该错误。 @汤姆
    • thnx ,但不幸的是无法使用线程中的任何给定解决方案来解决它。之后,我尝试使用以下命令将 gdrive 安装到 colab:“from google.colab import drive drive.mount('/content/gdrive')”,然后我使用了旧的 json 文件路径:PATH_TO_CREDENTIAL = '/content/gdrive/MyDrive /Colab Notebooks/client_secret.json' 现在它可以工作了:)
    猜你喜欢
    • 2021-05-14
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2019-11-10
    • 1970-01-01
    • 2021-10-05
    • 2021-06-13
    相关资源
    最近更新 更多