繁体   English   中英

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

[英]How to search for specific files in google drive?

我从 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()

我想要的是搜索谷歌驱动器中存在的文件。

执行普通的 file.list 将返回您的谷歌驱动器根目录中的所有文件,没有特殊顺序。

我不知道在哪里提供文件夹 ID 来查找文件?

要搜索特定文件夹中的所有文件,您需要使用 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)',

您可能想查看搜索文件和文件夹,它有一些有趣的示例。

如果它们存在,则可以,找到文件消息。 如果不是,则找不到文件

如果您正在搜索特定文件名,并且该名称不存在,您可能会从 API 得到一个空响应而不是错误。 因此,只需测试是否有任何文件返回就会告诉您是否找到了文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM