Recursively iterate through all subdirectories using pathlib

前端 未结 5 1275
清酒与你
清酒与你 2020-12-01 15:36

How can I use pathlib to recursively iterate over all subdirectories of a given directory?

p = Path(\'docs\')
for child in p.iterdir(): child
相关标签:
5条回答
  • 2020-12-01 15:59

    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.

    0 讨论(0)
  • 2020-12-01 16:03

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

    path = Path("docs")
    for p in path.rglob("*"):
         print(p.name)
    
    0 讨论(0)
  • 2020-12-01 16:09

    You can use the glob method of a Path object:

    p = Path('docs')
    for i in p.glob('**/*'):
         print(i.name)
    
    0 讨论(0)
  • 2020-12-01 16:16

    Use list comprehensions:

    (1) [f.name for f in p.glob("**/*")]  # or
    (2) [f.name for f in p.rglob("*")]
    

    You can add if f.is_file() or if f.is_dir() to (1) or (2) if you want to target files only or directories only, respectively. Or replace "*" with some pattern like "*.txt" if you want to target .txt files only.

    See this quick guide.

    0 讨论(0)
  • 2020-12-01 16:21

    To find just folders the right glob string is:

    '**/'
    

    So to find all the paths for all the folders in your path do this:

    p = Path('docs')
    for child in p.glob('**/'):
        print(child)
    

    If you just want the folder names without the paths then print the name of the folder like so:

    p = Path('docs')
    for child in p.glob('**/'):
        print(child.name)
    
    0 讨论(0)
提交回复
热议问题