Getting a list of all subdirectories in the current directory

后端 未结 29 2375
一个人的身影
一个人的身影 2020-11-22 08:02

Is there a way to return a list of all the subdirectories in the current directory in Python?

I know you can do this with files, but I need to get the list of direct

29条回答
  •  有刺的猬
    2020-11-22 08:34

    I've had a similar question recently, and I found out that the best answer for python 3.6 (as user havlock added) is to use os.scandir. Since it seems there is no solution using it, I'll add my own. First, a non-recursive solution that lists only the subdirectories directly under the root directory.

    def get_dirlist(rootdir):
    
        dirlist = []
    
        with os.scandir(rootdir) as rit:
            for entry in rit:
                if not entry.name.startswith('.') and entry.is_dir():
                    dirlist.append(entry.path)
    
        dirlist.sort() # Optional, in case you want sorted directory names
        return dirlist
    

    The recursive version would look like this:

    def get_dirlist(rootdir):
    
        dirlist = []
    
        with os.scandir(rootdir) as rit:
            for entry in rit:
                if not entry.name.startswith('.') and entry.is_dir():
                    dirlist.append(entry.path)
                    dirlist += get_dirlist(entry.path)
    
        dirlist.sort() # Optional, in case you want sorted directory names
        return dirlist
    

    keep in mind that entry.path wields the absolute path to the subdirectory. In case you only need the folder name, you can use entry.name instead. Refer to os.DirEntry for additional details about the entry object.

提交回复
热议问题