0

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?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • You seem to have already got the idea of what to do. Just recursively visit each non-hidden subfolder within a folder and return the non-hidden files. Have you attempted to implement this code already? Where did you get stuck? – Tom McLean Jul 07 '21 at 18:33
  • Thanks for the reply. I really just know `path.rglob("*")` which iterates over everything. No idea how to stop that at hidden directories. – Nico Schlömer Jul 07 '21 at 18:36
  • If the hidden file by your definition is just something that starts with '.', you'd probably just do something like iterating over the `rglob()` output, and at the top of your loop, `if currPath.name.startswith('.'):` with a `continue` statement to skip the loop iteration. You might also have to keep a list of directories that you consider hidden, and prune those paths that are in the blacklist. – Ben Y Jul 07 '21 at 19:04

1 Answers1

3

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('.')))
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Timus
  • 10,974
  • 5
  • 14
  • 28
  • Wouldn't you need a `list()` to make use of the generator? Printing it will probably give you the generator object, right? – Ben Y Jul 07 '21 at 19:21
  • 1
    @BenY The `*` is for the printing. I made a generator because he wants to _recursively iterate over ..._ – Timus Jul 07 '21 at 19:23
  • Sorry, missed the asterisk when I tried your code out. – Ben Y Jul 07 '21 at 19:42