首页 > 解决方案 > 如何找到谷歌驱动器的特定文件ID?

问题描述

在这段代码中,我根据其名称找到了一个特定的文件夹 ID。但我想根据其名称查找特定的文件 ID。怎么做?

def findId(self, filename):
    page_token = None
    while True:
        response = self.service.files().list(q="name = '"+ filename +"' and mimeType = 'application/vnd.google-apps.folder'",
                                                  spaces='drive',
                                                  fields='nextPageToken, files(id, name)',
                                                  pageToken=page_token).execute()
        for file in response.get('files', []):
            print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break

标签: pythonpython-3.xgoogle-drive-api

解决方案


让我们看看 file.list 方法的 q 参数实际上是如何工作的。这个 opitno 可以让你搜索很多东西,名字只是其中之一。

首先要记住的是 Google 驱动器中的所有内容都是一个文件,并且它有一个 fileid。因此,您当前的搜索正在搜索具有文件名名称和内部 google drive mime 文件夹类型的文件。

name = '"+ filename +"' and mimeType = 'application/vnd.google-apps.folder'",

然后,您可以将其切换为仅在名称后搜索,然后返回具有与该名称匹配的任何 mimetype 的所有文件。

name = '"+ filename +"'"

然后,您将获得与该名称匹配的所有文件的列表,然后问题是您的驱动器帐户上是否有多个与该名称匹配的文件。

def findId(self, filename):
    page_token = None
    while True:
        response = self.service.files().list(q="name = '"+ filename +"'",
                                                  spaces='drive',
                                                  fields='nextPageToken, files(id, name)',
                                                  pageToken=page_token).execute()
        for file in response.get('files', []):
            print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break

您可能会发现一些有趣的文档,其中详细介绍了您可以使用 Q 参数搜索 文件发送哪些选项代码本身在 C# 中。


推荐阅读