0

我的 Google 驱动器中有这样的文件夹结构

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

返回所有文件和文件夹的代码

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

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"]}]

我尝试从上面的列表创建完整路径的代码:

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")

输出:

{'sub4': 'subID4'}

预期输出:

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

编辑:预期输出解释:

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

1 回答 1

1

我认为你的list()功能有问题。

如果我尝试修复您的walk()功能,我最终会得到:

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)}

换句话说:部分解析实际上是在树之外完成的。太丑了

我认为你的list()函数的结果应该包含一个根节点。

于 2020-05-10T04:03:41.820 回答