What is the Python way to walk a directory tree?

后端 未结 11 1619
走了就别回头了
走了就别回头了 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:01

    I've not tested this extensively yet, but I believe this will expand the os.walk generator, join dirnames to all the file paths, and flatten the resulting list; To give a straight up list of concrete files in your search path.

    import itertools
    import os
    
    def find(input_path):
        return itertools.chain(
            *list(
                list(os.path.join(dirname, fname) for fname in files)
                for dirname, _, files in os.walk(input_path)
            )
        )
    

提交回复
热议问题