如何列出特定google驱动器目录中的所有文件

2024-05-28 23:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

按文件夹ID列出特定google驱动器目录的所有文件的最佳方式是什么。如果我构建了如下服务,下一步是什么?找不到对我有用的东西。thsi示例中的服务帐户文件是一个带有令牌的json文件

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = service_account_file 
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = discovery.build('drive', 'v3', credentials=credentials)

Tags: 文件目录文件夹idservicegoogleaccountdrive
2条回答

我相信你的目标如下

  • 您希望使用python的服务帐户检索特定文件夹下的文件列表

在这种情况下,我想提出以下两种模式

模式1:

在这个模式中,使用了带有googleapis for python的驱动API中的“Files:list”方法。但在这种情况下,不会检索特定文件夹中子文件夹中的文件

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = service_account_file
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)

topFolderId = '###' # Please set the folder of the top folder ID.

items = []
pageToken = ""
while pageToken is not None:
    response = service.files().list(q="'" + topFolderId + "' in parents", pageSize=1000, pageToken=pageToken, fields="nextPageToken, files(id, name)").execute()
    items.extend(response.get('files', []))
    pageToken = response.get('nextPageToken')

print(items)
  • q="'" + topFolderId + "' in parents"表示文件列表就在topFolderId文件夹下检索
  • 使用pageSize=1000时,可以减少驱动器API的使用次数

模式2:

在这个模式中,使用了getfilelistpy库。在这种情况下,还可以检索特定文件夹子文件夹中的文件。首先,请按如下方式安装库

$ pip install getfilelistpy

示例脚本如下所示

from google.oauth2 import service_account
from getfilelistpy import getfilelist

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = service_account_file
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

topFolderId = '###' # Please set the folder of the top folder ID.
resource = {
    "service_account": credentials,
    "id": topFolderId,
    "fields": "files(name,id)",
}
res = getfilelist.GetFileList(resource)
print(dict(res))
  • 在这个库中,可以使用用于python的googleapis驱动API中的“文件:列表”方法搜索特定文件夹中的子文件夹

参考文献:

file.list方法有一个名为q的参数。您可以使用q to search来处理目录中的文件之类的内容

假设您知道正在查找的文件夹的文件id,您可以执行“文件夹中的父文件夹id”

这将返回该文件夹中的所有文件

page_token = None
while True:
    response = drive_service.files().list(q="parents in 'YOURFOLDERIDHERE'",
                                          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

相关问题 更多 >

    热门问题