python - 如何使用python从驱动器的文件夹中检索文件?
问题描述
我是驱动器 API 的新手,我正在尝试从名为“users”的文件夹中访问文件。因此,为了导航到名为“用户”的文件夹,我使用了查询
q="name = 'users' and mimeType='application/vnd.google-apps.folder'"
但查询只检索名为“用户”的文件。我的动机是遍历名为“users”的文件夹的内容。我怎样才能做到这一点?
我的目录用户的流程如下所示
>Users
> 1
>1.json
>2
>2.json
>3
> 3.json
我需要检索 json 文件
results = service.files().list(q="name = 'users' and mimeType='application/vnd.google-apps.folder'",spaces = 'drive').execute()
items = results.get('files', [])
print(type(items))
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
解决方案
使用查询字符串参数,您的工作进展顺利。查看文档页面,了解查询文件的选项。
在您的情况下,您想要搜索文件夹中的文件,查看文档中的搜索文件页面很明显您想要包含该子句<file-id> in parents
。
q= "'1ObbqxfTThIsATestIdiieLBz' in parents"
之后,您可以递归地遍历文件,您可以检查 mime 类型以查看文件是否实际上是文件夹。
编辑:如果您想要一个功能来打印所有文件,您可以查看此示例:
def files_in_folder(folder_id, service, deep=0):
"""Prints all the files inside folder_id recursively
Args:
folder_id: The id of the current folder
service: A google Drive service to execute requests
deep: Keep track of how many sub-folder have we been
"""
files = service.files().list(q="'{}' in parents".format(folder_id)).execute()
for _file in files["files"]:
print(" "*deep + _file["name"])
# Check if the file is a folder and print all the files inside
if _file["mimeType"] == "application/vnd.google-apps.folder":
files_in_folder(_file["id"], service, deep=deep+1)
在我的情况下,从我得到的文件夹中调用此函数root
:
Folder1
Folder2
Test
Copy of Copy for posting
File
Untitled form
推荐阅读
- google-bigquery - 如何在大查询中操作 SAFE_ORDINAL
- c++ - 根据它们的值进行 std::map 比较的有效方法
- java - 如何在jersey的服务层实现一个可以获取请求和响应信息的功能
- python - 在 Django 表单中创建日期范围滑块
- javascript - oracle apex 替换函数 javascript
- r - 部分行标签热图 - R
- html - React-Redux 未在输入/文本区域框中正确呈现数据
- c# - 当第一个节点关闭时,如何设置 Replica-set 自动切换到另一个节点?
- apache-kafka - java.io.IOException:在 kafka.utils.NetworkClientBlockingOps$.awaitReady 处连接到 kafka VIA 端口 6667 失败
- php - PHP 使用 $_POST 在 IF 语句的错误条件内执行 sql