Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.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
Google drive api 使用gspread库检查工作簿是否存在?_Google Drive Api_Gspread - Fatal编程技术网

Google drive api 使用gspread库检查工作簿是否存在?

Google drive api 使用gspread库检查工作簿是否存在?,google-drive-api,gspread,Google Drive Api,Gspread,如何使用gspread库检查工作簿是否存在? 我的问题是,如果我第二次运行gspread.create(title),它不会重写上一个文件,而是用相同的名称创建另一个文件。有什么办法可以避免吗 谢谢。 Petro.我相信你的目标如下 您希望使用电子表格名称检查电子表格是否存在 当电子表格不存在时,您需要创建新的电子表格,并检索创建的电子表格 当电子表格存在时,您希望检索现有的电子表格 您想使用gspread 在这种情况下,为了使用电子表格名称检查电子表格是否存在,需要使用驱动API。示例脚本

如何使用gspread库检查工作簿是否存在? 我的问题是,如果我第二次运行gspread.create(title),它不会重写上一个文件,而是用相同的名称创建另一个文件。有什么办法可以避免吗

谢谢。
Petro.

我相信你的目标如下

  • 您希望使用电子表格名称检查电子表格是否存在
  • 当电子表格不存在时,您需要创建新的电子表格,并检索创建的电子表格
  • 当电子表格存在时,您希望检索现有的电子表格
  • 您想使用gspread
在这种情况下,为了使用电子表格名称检查电子表格是否存在,需要使用驱动API。示例脚本如下所示

示例脚本: 请复制并粘贴以下脚本。此脚本不包括授权脚本。因此,请添加用于检索
client=gspread.authorize(凭据)
的脚本

  • 在这种情况下。请添加
    导入请求
    。驱动器API中的“文件:列表”方法与
    request
    library一起使用
  • 当运行上述脚本时,首先,使用驱动器API v3中的“文件:列表”方法搜索
    spreadsheetName
    的电子表格名称。并且,当电子表格存在时,现有电子表格将作为gspread的电子表格对象进行检索。当电子表格不存在时,将创建新的电子表格,并检索为gspread创建的电子表格对象
  • 如果要从特定文件夹中搜索电子表格,请使用
    url=”https://www.googleapis.com/drive/v3/files?q=mimeType%3D%27application%2Fvnd.google-应用程序。电子表格%27%20和%20name%3D%27“+电子表格名+%27%20和%20%27“+文件夹ID+%27%20in%20parents”
    • 在这种情况下,请设置
      folderId
注:
  • 如果发生与作用域相关的错误,请包括
    https://www.googleapis.com/auth/drive
    https://www.googleapis.com/auth/drive.readonly
参考:
spreadsheetName = "sample Spreadsheet name" # Please set the Spreadsheet name you want to check.

client = gspread.authorize(credentials)
url = "https://www.googleapis.com/drive/v3/files?q=mimeType%3D%27application%2Fvnd.google-apps.spreadsheet%27%20and%20name%3D%27" + spreadsheetName + "%27%20"
res = requests.get(url, headers={"Authorization": "Bearer " + credentials.access_token})
files = res.json().get("files")
spreadsheet = client.open_by_key(files[0]['id']) if files else client.create(spreadsheetName)

# Sample script for testing "spreadsheet".
sheetNameOf1stTab = spreadsheet.sheet1.title
print(sheetNameOf1stTab)