0

I have a directory, and I want to get all the files (no directories) inside it, and all the files inside of any of its subdirectories and so on.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103

1 Answers1

0

Use glob or rglob to recursively iterate over both files and directories and then skip anything that doesn't return True for Path.is_file()

from pathlib import Path

def iter_files(path):
    for file_or_directory in path.rglob("*"):
        if file_or_directory.is_file():
            yield file_or_directory

Then you can use that generator like this

my_path = Path("/some/path/here")

for my_file in iter_files(my_path):
    do_whatever(my_file)

You can use the same principle in a list comprehension

files = [path for path in my_path.rglob("*") if path.is_file()]
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103