Created
July 14, 2021 22:35
-
-
Save wgwoods/bf3a711b6c4475c39cb9b4b17e69f277 to your computer and use it in GitHub Desktop.
A pathlib-based way to walk the filesys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python3 | |
| from pathlib import Path | |
| # Define an action that you can send into the generator | |
| SKIPDIR = 1 | |
| # Path walkin' generator coroutine | |
| def walk(topdir='.'): | |
| for p in Path(topdir).iterdir(): | |
| action = yield p | |
| if p.is_dir() and action is not SKIPDIR: | |
| yield from walk(p) | |
| # Example use: just list files, skipping .git | |
| if __name__ == '__main__': | |
| walker = walk() | |
| for p in walker: | |
| # If we have a directory we don't want to descend, tell the walker | |
| if p.is_dir() and p.name == '.git': | |
| walker.send(SKIPDIR) | |
| # Process files. For this example we're just printing them. | |
| if p.is_file(): | |
| print(p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment