如何找到 google 驱动器的特定文件 ID?

How to find a particular file id of google drive?

在此代码中,我根据其名称找到了一个特定的文件夹 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

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

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

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

然后您可以将其切换为仅搜索名称,然后 return 具有与该名称匹配的任何 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 参数发送哪些选项 search files 我还有一个解释它的视频 Google drive API V3: Beginners to listing files and searching files 您可能会发现解释很有用,代码本身是用 C# 编写的。