简体   繁体   English

带递归的完整文件路径

[英]full file path with recursion

I got a folder structure like this in my Google drive我的 Google 驱动器中有这样的文件夹结构

 root
    |
    ├── folder1
    |   |
    │   ├── sub1
    |   |   |
    │   │   └── sub3
    |   |       |
    │   │       └── sub4
    |   |
    │   └── sub2
    |
    └── folder2
        |
        └── sub1

The code to return all files and folders返回所有文件和文件夹的代码

from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
from merge import drive

def List():
        store = file.Storage('storage.json')
        creds = store.get()
        DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
        files = []
        token = ""
        while True:
                f = DRIVE.files().list(pageToken=token,fields="files(name,id,parents),nextPageToken").execute()
                files.extend(f["files"])
                token = f.get("nextPageToken","q")
                if token=="q":
                        break
        return files

This List() returns这个List()返回

 [{"name":"folder1", "id":"folderID1", "parents": ["rootID"]},
  {"name":"folder2", "id":"folderID2", "parents": ["rootID"]},
  {"name":"sub1", "id":"subID1", "parents": ["folderID1"]},
  {"name":"sub1", "id":"subID11", "parents": ["folderID2"]},
  {"name":"sub2", "id":"subID2", "parents": ["folderID1"]},
  {"name":"sub3", "id":"subID3", "parents": ["subID1"]},
  {"name":"sub4", "id":"subID4", "parents": ["subID3"]}]

The code I tried to create full path from above list:我尝试从上面的列表创建完整路径的代码:

def walk(ID, files, dic):
    for file in files:
        if ID == file["parents"][0]:
            dic = walk(file["id"], files, {file["name"]:dic})
    return {file["name"]:file["id"]}

walk("rootID", List(), "root")

output: output:

{'sub4': 'subID4'}

Expected Output:预期 Output:

{'root': {'folder1': {'sub1': {'sub3': {'sub4': 'subID4'}}, 'sub2': 'sub2ID'},
          'folder2': {'sub1': 'subID11'}}}

EDIT: Expected Output Explanation:编辑:预期 Output 解释:

{root_directory : {sub_folders:...{last_sub_folder: ID}...}}

I think there's something wrong with your list() function.我认为您的list() function 有问题。

If I would try to repair your walk() function, I would end up with:如果我想修复你的walk() function,我最终会得到:

def walk2(ID, files):
    result = {}
    for file in files:
        if ID == file["parents"][0]:
            result[file["name"]] = walk2(file["id"], files)
    if not result:
        return ID
    return result

test = {"root": walk2("rootID", myList)}

In other words: Part of the parsing would actually be done outside the tree.换句话说:部分解析实际上是在树之外完成的。 That's ugly.太丑了

I think the result of your list() function should contain a root node.我认为您的list() function 的结果应该包含一个根节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM