如何动态迭代子目录

清风

我在多种情况下都遇到过这个问题。

这里的一个用例是,假设我有一个目录结构,其中可以包含未知的子目录层,并且我想获取 rootdir 下的文件总数。动态迭代这棵树的最佳方法是什么?

这是文件夹结构的示例:

rootdir
   -> subdir1
     ->file1
          -> subsubdir1
                 -> file1
                 -> file2
          -> subsubdir2
                 -> file1
          -> subsubdir3
                 -> file1
                 -> subsubsubdir
                    -> file1
   -> subdir2
          -> subsubdirA
                 -> file1
                 -> file2
          -> subsubdirB
                 -> file1
                 -> file2

我从 API 调用中获取文件夹结构,而不是直接从文件系统中获取。这是 api 响应的一部分。假设这是我通过调用 rootdir 得到的结果,然后我想保存子文件夹 id [1,2],然后进入每个子文件夹并迭代相同的过程来查找子文件夹是否存在,同时保持计数文件。

响应包含一个 total_count,它是项目的数量(一个子文件夹将被计为 1)。所以我需要跟踪子文件夹 id,并为每个子文件夹启动一个新的 api 调用,以获取每个子文件夹(以及潜在的子文件夹)中的文件数,同时跟踪总文件数文件。(希望我解释清楚了。如果有任何不清楚的地方,请随时发表评论。)

{

"item_collection":{"total_count":3,
    "entries":[
    {"type":"folder","id":"1","sequence_id":"0","etag":"0"},
    {"type":"folder","id":"2","sequence_id":"0","etag":"0"},
    {"type":"file","id":"3","file_version"{"type":"file_version","id":"303835527128"},"sequence_id":"0","etag":"0",}
    ],
]}
}

这是我到目前为止所拥有的,但我不确定如何跟踪每个子文件夹并动态迭代它们。任何帮助表示赞赏!

def total_file_count(client, folder_id):
    total_file_count = 0
    subfolder_ids = []
    folder = client.get_folder(folder_id=folder_id)
    item_count = folder['item_collection']['total_count']
    subfolder = True

    if item_count > 0:
        while subfolder:
            for i in folder['item_collection']['entries']:
                if i['type']=='folder':
                    subfolder_ids.append(i['id'])
                elif i['type']=='file':
                    total_file_count += 1

                subfolder = False if not subfolder_ids

    return total_file_count
MxLDevs

这是使用 while 循环的一般方法。这个想法是您从文件夹 ID 列表(您作为根提供)开始,然后从您获得的条目中,您将添加任何要搜索的文件夹到该列表中。因此,尽管仍有文件夹需要检查,但您仍会不断提出请求并累加文件数。

def get_file_count(client, folder_id):
  count = 0
  folders = [folder_id]
  while len(folders) > 0:
    id = folders.pop(0)
    data = client.get_folder(id)
    entries = data["item_collection"]["entries"]
    for entry in entries:
      if entry["type"] == "folder":
        folders.append(entry["id"])
      else:
        count += 1    
  return count

您可能会也可能无法复制和粘贴它,但这仅用于说明目的。

理想情况下,如果有一个 API 可以同时为您提供所有条目,那就太好了,但我可以想象很多用例是不可能的,因此您将不得不一次又一次地单独发出请求。

解决方案没有优化。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章