Created
December 5, 2021 12:58
-
-
Save tmck-code/96b293ae0576782424f821338d5ccf7f to your computer and use it in GitHub Desktop.
Python dir walk recursive
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/env python3 | |
| import os | |
| from collections.abc import Iterable | |
| from pathlib import Path | |
| def os_walkr(dirpath: str, log=False) -> Iterable[Path]: | |
| 'traverse root directory, and list directories as dirs and files as files' | |
| for root, dirs, fpaths in os.walk(dirpath): | |
| path = root.split(os.sep) | |
| if log: | |
| print((len(path) - 1) * '---', os.path.basename(root)) | |
| for fname in fpaths: | |
| if log: | |
| print(len(path) * '---', fname) | |
| yield Path(os.path.join(root, fname)) |
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/env python3 | |
| import os | |
| from pathlib import Path | |
| def path_walkr(dirpath: Path, log: bool=False) -> Iterable[Path]: | |
| for x in dirpath.iterdir(): | |
| if log: | |
| print((len(dirpath.parts)+1) * '---', os.path.basename(x)) | |
| if x.is_file(): | |
| yield x | |
| if x.is_dir(): | |
| yield from path_walkr(x, log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment