首页 > 解决方案 > 如何使用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']))

标签: pythongoogle-apigoogle-drive-api

解决方案


使用查询字符串参数,您的工作进展顺利。查看文档页面,了解查询文件的选项。

在您的情况下,您想要搜索文件夹中的文件,查看文档中的搜索文件页面很明显您想要包含该子句<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

推荐阅读