【发布时间】:2020-08-16 23:25:36
【问题描述】:
我想在 Python 中递归遍历一个目录并获取所有子目录和文件的嵌套列表。 我已经找到了几十个解决方案来解决第一部分(递归遍历目录),但是没有一个允许我以我需要的格式获得输出。
对于使用哪些库没有限制/偏好。我尝试使用 pathlib,但 os.walk() 也很好。此外,它必须是一个递归函数。循环就好了。
我有以下结构:
root
├── file1.txt
├── file2.txt
├── sub1
│ ├── subfile1.txt
│ └── subsub
│ └── subsubfile1.txt
└── sub2
我需要结果是这样的嵌套列表:
[
{
'name': 'file1.txt'
},
{
'name': 'file2.txt'
},
{
'name': 'sub1',
'children': [
{
'name': 'subfile1.txt'
},
{
'name': 'subsub',
'children': [
{
'name': 'subsubfile1.txt'
}
]
}
]
},
{
'name': 'sub2'.
'children': []
}
]
这是我已经走了多远,但它没有给出正确的结果:
from pathlib import Path
def walk(path: Path, result: list) -> list:
for p in path.iterdir():
if p.is_file():
result.append({
'name': p.name
})
yield result
else:
result.append({
'name': p.name,
'children': list(walk(p, result))
})
walk(Path('root'), []) # initial call
除了这段代码不起作用之外,我还遇到了递归集合的问题。当我尝试漂亮地打印它时,它显示:
'children': [ <Recursion on list with id=4598812496>,
<Recursion on list with id=4598812496>],
'name': 'sub1'},
是否可以将该 Recursion 对象作为列表获取?
如果有人想知道为什么我需要这种结构而不是像 pathlib.glob() 返回的那种扁平列表,那是因为这个列表将被我 API 另一端的这段代码使用: https://vuetifyjs.com/en/components/treeview/#slots
【问题讨论】:
标签: python recursion treeview pathlib