List directories with a specified depth in Python

后端 未结 4 1561
故里飘歌
故里飘歌 2020-12-28 14:26

I\'m want a function to return a list with directories with a specified path and a fixed depth and soon realized there a few alternatives. I\'m using os.walk quite a lot but

4条回答
  •  执念已碎
    2020-12-28 15:22

    I really like phihag's answer. I adapted it to suit my needs.

    import fnmatch,glob
    def fileNamesRetrieve( top, maxDepth, fnMask  ):
        someFiles = []
        for d in range( 1, maxDepth+1 ):
            maxGlob = "/".join( "*" * d )
            topGlob = os.path.join( top, maxGlob )
            allFiles = glob.glob( topGlob )
            someFiles.extend( [ f for f in allFiles if fnmatch.fnmatch( os.path.basename( f ), fnMask ) ] )
        return someFiles
    

    I guess I could also make it a generator with something like this:

    def fileNamesRetrieve( top, maxDepth, fnMask  ):
        for d in range( 1, maxDepth+1 ):
            maxGlob = "/".join( "*" * d )
            topGlob = os.path.join( top, maxGlob )
            allFiles = glob.glob( topGlob )
            if fnmatch.fnmatch( os.path.basename( f ), fnMask ):
                yield f
    

    Critique welcome.

提交回复
热议问题