簡體   English   中英

帶遞歸的完整文件路徑

[英]full file path with recursion

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

output:

{'sub4': 'subID4'}

預期 Output:

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

編輯:預期 Output 解釋:

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

我認為您的list() function 有問題。

如果我想修復你的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)}

換句話說:部分解析實際上是在樹之外完成的。 太丑了

我認為您的list() function 的結果應該包含一個根節點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM