Skip to content

Instantly share code, notes, and snippets.

@tmck-code
Created December 5, 2021 12:58
Show Gist options
  • Select an option

  • Save tmck-code/96b293ae0576782424f821338d5ccf7f to your computer and use it in GitHub Desktop.

Select an option

Save tmck-code/96b293ae0576782424f821338d5ccf7f to your computer and use it in GitHub Desktop.
Python dir walk recursive
#!/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))
#!/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