What is the Python way to walk a directory tree?

后端 未结 11 1608
走了就别回头了
走了就别回头了 2020-12-06 09:52

I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I\'m using Python 3.2

from os import *
from os.pat         


        
11条回答
  •  抹茶落季
    2020-12-06 10:16

    Since Python 3.4 there is new module pathlib. So to get all dirs and files one can do:

    from pathlib import Path
    
    dirs = [str(item) for item in Path(path).iterdir() if item.is_dir()]
    files = [str(item) for item in Path(path).iterdir() if item.is_file()]
    

提交回复
热议问题