Search code examples
pythonpathlib

recursively get all files except the hidden ones with pathlib


I would like to use pathlib to recursively iterate over all files of a given path, except those which are hidden or are in hidden directories. E.g., from

|
|- a.txt
|- .b.txt
|- a/
|  |- c.txt
|  |- .d.txt
|  +- c/
|     +- e.txt
|- .b/
   +- f.txt

I would like to get

a.txt
a/c.txt
a/c/e.txt

Any hints?


Solution

  • You could do something like this:

    from pathlib import Path
    
    def non_hidden_files(root):
        for path in root.glob('*'):
            if not path.name.startswith('.'):
                if path.is_file():
                    yield str(path)
                else:
                    yield from non_hidden_files(path)
    
    print(*non_hidden_files(Path('.')))