Python Google Drive API - list the entire drive file tree

前端 未结 4 1694
走了就别回头了
走了就别回头了 2020-12-10 06:02

I\'m building a python application that uses the Google drive APIs, so fare the development is good but I have a problem to retrieve the entire Google drive file tree, I nee

4条回答
  •  一生所求
    2020-12-10 06:17

    I agree with @pinoyyid - Google drive is not a typical tree structure.

    BUT, for printing the folder structure I would still consider using a tree visualization library (for example like treelib).

    Below is a full solution for printing your google drive file system recursively.

    from treelib import Node, Tree
    
    from pydrive.auth import GoogleAuth
    from pydrive.drive import GoogleDrive
    
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)
    
    ### Helper functions ### 
    def get_children(root_folder_id):
        str = "\'" + root_folder_id + "\'" + " in parents and trashed=false"
        file_list = drive.ListFile({'q': str}).GetList()
        return file_list
    
    def get_folder_id(root_folder_id, root_folder_title):
        file_list = get_children(root_folder_id)
        for file in file_list:
            if(file['title'] == root_folder_title):
                return file['id']
    
    def add_children_to_tree(tree, file_list, parent_id):
        for file in file_list:
            tree.create_node(file['title'], file['id'], parent=parent_id)
            print('parent: %s, title: %s, id: %s' % (parent_id, file['title'], file['id']))
    
    ### Recursion over all children ### 
    def populate_tree_recursively(tree,parent_id):
        children = get_children(parent_id)
        add_children_to_tree(tree, children, parent_id)
        if(len(children) > 0):
            for child in children:
                populate_tree_recursively(tree, child['id'])
    
    
    ### Create tree and start populating from root ###
    def main():
        root_folder_title = "your-root-folder"
        root_folder_id = get_folder_id("root", root_folder_title)
    
        tree = Tree()
        tree.create_node(root_folder_title, root_folder_id)
        populate_tree_recursively(tree, root_folder_id)
        tree.show()
    
    if __name__ == "__main__":
        main()
    

提交回复
热议问题