【问题标题】:Get the entire directory structure of a directory as list获取目录的整个目录结构作为列表
【发布时间】:2022-01-18 21:57:08
【问题描述】:

所以我正在制作一个 GUI,它需要一个包含预配置目录的目录结构的列表。格式可能是这样的:

{"base_folder":
  [
    "file1.txt",
    "file2.txt",
    {"directory1":
      [
        "nested_image.png",
        {"nested_directory":
          [
            "deep_video.mp4",
            "notes.txt"
          ]
        },
        "another_image.png",
        "not_a_file_type.thisisafile"
      ]
    },
    "game.exe",
    "mac_port_of_game.app",    # yeah I know that a .app is a bundle but can't be bothered
                               # to make the entire bundle structure
    "linux_port_of_game.elf",
    {"coding_stuff":
      [
        "code.py",
        "morecode.c"
      ]
    }
  [
}

格式不一定要完全一样,但是否有内置函数,可能在os 模块中可以做到这一点?

【问题讨论】:

  • 我不这么认为,但是用os.walk()写应该不难。
  • 那么,您在查看文档时发现了什么?
  • 不,没有内置的——为什么会有?
  • @TheMystZ 您是否尝试过建议的解决方案?

标签: python list directory


【解决方案1】:

可能是这样的递归?

from pathlib import Path
import json

def get_files(root, tree):
    subtree = {root.name: []}
    files = list(root.glob('*'))

    for file in files:
        if file.is_file():
            subtree[root.name].append(file.name)
        else:
            subtree[root.name].append(get_files(file, tree))
    return subtree

root = Path(r'/Users/user/Desktop')
tree = get_files(root,[])
print(json.dumps(tree, indent=4, sort_keys=True))

【讨论】:

  • 谢谢,你的回答成功了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 2019-04-23
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多