-1

Original code :

for dir_name, dir_path, file_name in os.walk(dir):
    doSomething()

What can we use from pathlib module instead of os.walk().

Thankss....

prachi sutane
  • 13
  • 1
  • 8
  • Why is this down-voted? Just running into this because manipulating Path is much easier and to parse each path string into a Path instance appears to be quite wasteful with CPU-resources. – Bluehorn Jun 27 '23 at 20:26

1 Answers1

1

The short answer is : nothing. The pathlib module does not implement such a function.

However, implementing one yourself is fairly trivial :

def my_walk(mydir: pathlib.Path):
    '''like os.walk, but using pathlib.Path, and with fewer options'''
    subdirs = list(d for d in mydir.iterdir() if d.is_dir())
    files = list(f for f in mydir.iterdir() if f.is_file())
    yield mydir, subdirs, files
    for s in subdirs:
        yield from my_walk(s)

for dir_path, dir_names, file_names in os.walk('.'):
    print(dir_path, dir_names, file_names)

for dir_path, subdir_paths, file_paths in my_walk(pathlib.Path('.')):
    print(dir_path, subdir_paths, file_paths)

That being said, I'm not sure why it would not be simpler to import os and then os.walk.

Hoodlum
  • 950
  • 2
  • 13