2

I know that glob exists for this purpose and one can also use os.walk to get a list of all subdirectories and files inside a folder and use this to create a tree of all files and folders that exist inside a root directory. However, can one also use the Pathlib iterdir function to recursively iterate through all subdirectories inside a folder and store the paths to all files and the filenames like we can do so easily with os.walk?

I am asking this question since as per my knowledge, the Pathlib actually presents better way to do things already done by os and os.path.

quantum231
  • 2,420
  • 3
  • 31
  • 53
  • 1
    Please let me know if an answer already exists to this question. – quantum231 Jun 02 '21 at 00:37
  • 2
    Why can't you use `Path.glob` (**not** the glob module)? ie. https://stackoverflow.com/questions/50714469/recursively-iterate-through-all-subdirectories-using-pathlib – SuperStormer Jun 02 '21 at 00:44
  • I want to literally iterate through the root directory, comparing the folder name and filename with regular expressions and if they match, add the resulting file and full path into a list or dictionary. – quantum231 Jun 02 '21 at 01:00
  • 1
    Path.glob or just glob, what is the difference? – quantum231 Jun 02 '21 at 01:01

1 Answers1

0

If all you need is strings, or if you need to prune directories or control the order of traversal, then os.walk is the correct tool. For other tasks when you need Path objects then pathlib might be better.

For most use cases, at least those provided by os.path then pathlib can be simpler and more elegant. But, pathlib is not a better replacement for all related functionality in OS. Os.walk is a clear example of a use case that pathlib does not support as well.

julie
  • 172
  • 1
  • 6