Recursively iterate through all subdirectories using pathlib

前端 未结 5 1292
清酒与你
清酒与你 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 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.

提交回复
热议问题