如何在 google 驱动器中搜索特定文件?

How to search for specific files in google drive?

我从 Google 开发者网站上获取了这段代码,并对其进行了一些修改。但我想要的是搜索 Google 驱动器中存在的文件。我不知道在哪里给 folder id 找到文件?。如果它们存在,则 okay, the files are found 消息。如果不是那么 files are not found

import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

SCOPES = ['https://www.googleapis.com/auth/drive']    
def main():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('drive', 'v3', credentials=creds)
    filename = 'Image'
    page_token = None
    while True:
        response = service.files().list(q="name contains '"+filename+"'",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()
        for file in response.get('files', []):
            # Process change
            print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break

if __name__ == '__main__':
    main()

I want is to search for the files that are present in Google drive.

正常 file.list 将 return 您的 google 驱动器根目录中的所有文件无特殊顺序。

I don't know where to give the folder id to find the files?.

要搜索特定文件夹中的所有文件,您需要使用 Q 搜索参数的 parents in 选项。

response = service.files().list(q="parents in '"+ Folder ID +"'",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()

我建议执行如下操作,首先搜索文件夹,这将帮助您找到可以在上面的请求中使用的文件夹的文件 ID。

response = service.files().list(q="name = '"+ folder name +"' and mimeType = 'application/vnd.google-apps.folder'",
                                                  spaces='drive',
                                                  fields='nextPageToken, files(id, name)',

您可能想查看 Search for files and folders 它有一些有趣的示例。

If they exist then okay, the files are found message. If not then files are not found

如果您正在搜索特定的文件名,而该名称不存在,您可能会从 API 返回一个空响应,而不是错误。所以简单地测试是否有任何文件 returned 会告诉你是否找到文件。