递归遍历目录和 return 包含子目录和文件的嵌套列表 Python
Traverse directories recursively and return a nested list with the subdirectories and files in Python
我想递归遍历 Python 中的一个目录并获得所有子目录和文件的嵌套列表。
我已经找到了数十种解决方案来解决第一部分(递归遍历目录),但其中 none 允许我以我需要的格式获得输出。
没有 restrictions/preferences 要使用的库。我尝试使用 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() 返回的那样的平面列表,那是因为这个列表将被我的 [=39] 另一端的代码使用=]:
https://vuetifyjs.com/en/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)]
当运行 上述函数在与您的示例类似的文件结构上时,结果为:
import json
print(json.dumps(to_tree(), indent=4))
输出:
[
{
"name": "file1.txt"
},
{
"name": "file2.txt"
},
{
"name": "sub1",
"children": [
{
"name": "subfile1.txt"
},
{
"name": "subsub",
"children": [
{
"name": "subsubfile1.txt"
}
]
}
]
},
{
"name": "sub2",
"children": []
}
]
我想递归遍历 Python 中的一个目录并获得所有子目录和文件的嵌套列表。 我已经找到了数十种解决方案来解决第一部分(递归遍历目录),但其中 none 允许我以我需要的格式获得输出。
没有 restrictions/preferences 要使用的库。我尝试使用 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() 返回的那样的平面列表,那是因为这个列表将被我的 [=39] 另一端的代码使用=]: https://vuetifyjs.com/en/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)]
当运行 上述函数在与您的示例类似的文件结构上时,结果为:
import json
print(json.dumps(to_tree(), indent=4))
输出:
[
{
"name": "file1.txt"
},
{
"name": "file2.txt"
},
{
"name": "sub1",
"children": [
{
"name": "subfile1.txt"
},
{
"name": "subsub",
"children": [
{
"name": "subsubfile1.txt"
}
]
}
]
},
{
"name": "sub2",
"children": []
}
]