python - 如何列出特定谷歌驱动器目录Python中的所有文件
问题描述
按文件夹 ID 列出特定谷歌驱动器目录的所有文件的最佳方法是什么。如果我构建如下所示的服务,下一步是什么?找不到任何对我有用的东西。此示例中的 Service_Account_File 是带有令牌的 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)
解决方案
我相信你的目标如下。
- 您想使用带有 python 的服务帐户检索特定文件夹下的文件列表。
在这种情况下,我想提出以下两种模式。
模式一:
在此模式中,使用了 Drive API 中的“文件:列表”方法和 googleapis for python。但在这种情况下,不会检索特定文件夹中子文件夹中的文件。
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
,可以减少Drive API的使用次数。
模式二:
在此模式中,使用了一个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))
- 在这个库中,可以使用Drive API中的“Files:list”的方法使用googleapis for python搜索特定文件夹中的子文件夹。
参考:
推荐阅读
- python - 尝试使用套接字和 tkinter 制作服务器应用程序
- sql - 混合索引和非索引字段的Django过滤器的效率?
- powerbi - azure 中嵌入的 powerbi 是否没有管理工作区、报告等的门户?
- c++ - 在类中使用结构对象
- python - 如何仅为一个键更新字典中的集合?(Python)
- javascript - 如何在 NodeJS 的对象中嵌入来自方法的响应?
- git - git : 为 git merge --squash -X theirs 禁用自动合并
- javascript - 如何将我的 mongodb 连接到我的笔记本电脑?
- jquery - 不错的选择不工作附加附加
- android - 为什么我们不能在没有 youtube 官方应用的情况下使用 youtube api