[英]List with all the files in directories &subdirectories with path (Python)
[英]Traverse directories recursively and return a nested list with the subdirectories and files in Python
我想递归遍历 Python 中的目录并获取所有子目录和文件的嵌套列表。 我已经找到了几十个解决方案来解决第一部分(递归遍历目录),但没有一个允许我以我需要的格式获得 output。
使用哪些库没有限制/偏好。 我尝试使用 pathlib,但 os.walk() 也很好。 此外,它不必是递归 function。 一个循环就好了。
我有以下结构:
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'},
是否可以将递归 object 作为列表?
如果有人想知道为什么我需要这种结构而不是像 pathlib.glob() 返回的那种扁平列表,那是因为这个列表将被我的 API 另一侧的代码使用: https://vuetifyjs.com/ zh/components/treeview/#slots
您可以在递归中使用os.listdir
:
import os
def to_tree(s=os.getcwd()):
return [{'name':i} if os.path.isfile(f'{s}/{i}') else
{'name':i, 'children':to_tree(f'{s}/{i}')} for i in os.listdir(s)]
在与您的示例类似的文件结构上运行上面的 function 时,结果是:
import json
print(json.dumps(to_tree(), indent=4))
Output:
[
{
"name": "file1.txt"
},
{
"name": "file2.txt"
},
{
"name": "sub1",
"children": [
{
"name": "subfile1.txt"
},
{
"name": "subsub",
"children": [
{
"name": "subsubfile1.txt"
}
]
}
]
},
{
"name": "sub2",
"children": []
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.