使用pathlib递归遍历所有子目录
问题描述:
如何使用 pathlib 递归地迭代给定的所有子目录目录?
How can I use pathlib to recursively iterate over all subdirectories of a given directory?
p = Path('docs')
for child in p.iterdir(): child
似乎只遍历给定目录的直接子级.
only seems to iterate over the immediate children of a given directory.
我知道这对于os.walk()
或glob
是可行的,但是我想使用pathlib,因为我喜欢使用path对象.
I know this is possible with os.walk()
or glob
, but I want to use pathlib because I like working with the path objects.
答
您可以使用Path对象的rel ="noreferrer"> glob
方法:
You can use the glob
method of a Path
object:
p = Path('docs')
for i in p.glob('**/*'):
print(i.name)