Can I force python3's os.walk to visit directories in alphabetical order? how?

后端 未结 3 488
既然无缘
既然无缘 2020-12-09 15:03

I would like to know if it\'s possible to force os.walk in python3 to visit directories in alphabetical order. For example, here is a directory and some code that will walk

3条回答
  •  我在风中等你
    2020-12-09 15:29

    I know this has already been answered but I wanted to add one little detail and adding more than a single line of code in the comments is wonky.

    In addition to wanting the directories sorted I also wanted the files sorted so that my iteration through "gl" was consistent and predictable. To do this one more sort was required:

    for root, dirs, files in os.walk(gl['pwd']):
      dirs.sort()
      for filename in sorted(files):
        print(os.path.join(root, filename))
    

    And, with benefit of learning more about Python, a different (better) way:

    from pathlib import Path
    # Directories, per original question.
    [print(p) for p in sorted(Path(gl['pwd']).glob('**/*')) if p.is_dir()]
    # Files, like I usually need.
    [print(p) for p in sorted(Path(gl['pwd']).glob('**/*')) if p.is_file()]
    

提交回复
热议问题