Recursively iterate through all subdirectories usi

2019-06-15 16:00发布

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.

I know this is possible with os.walk() or glob, but I want to use pathlib because I like working with the path objects.

3条回答
Deceive 欺骗
2楼-- · 2019-06-15 16:33

Use Path.rglob (substitutes the leading ** in Path().glob("**/*")):

path = Path("docs")
for p in path.rglob("*"):
     print(p.name)
查看更多
欢心
3楼-- · 2019-06-15 16:43

You can use the glob method of a Path object:

p = Path('docs')
for i in p.glob('**/*'):
     print(i.name)
查看更多
做个烂人
4楼-- · 2019-06-15 16:49

pathlib has glob method where we can provide pattern as an argument.

For example : Path('abc').glob('**/*.txt') - It will look for current folder abc and all other subdirectories recursively to locate all txt files.

查看更多
登录 后发表回答