Getting a list of all subdirectories in the current directory

后端 未结 29 2419
一个人的身影
一个人的身影 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:33

    The easiest way:

    from pathlib import Path
    from glob import glob
    
    current_dir = Path.cwd()
    all_sub_dir_paths = glob(str(current_dir) + '/*/') # returns list of sub directory paths
    
    all_sub_dir_names = [Path(sub_dir).name for sub_dir in all_sub_dir_paths] 
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 08:34

    use a filter function os.path.isdir over os.listdir() something like this filter(os.path.isdir,[os.path.join(os.path.abspath('PATH'),p) for p in os.listdir('PATH/')])

    0 讨论(0)
  • 2020-11-22 08:35

    Listing Out only directories

    print("\nWe are listing out only the directories in current directory -")
    directories_in_curdir = filter(os.path.isdir, os.listdir(os.curdir))
    print(directories_in_curdir)
    

    Listing Out only files in current directory

    files = filter(os.path.isfile, os.listdir(os.curdir))
    print("\nThe following are the list of all files in the current directory -")
    print(files)
    
    0 讨论(0)
  • 2020-11-22 08:36

    By joining multiple solutions from here, this is what I ended up using:

    import os
    import glob
    
    def list_dirs(path):
        return [os.path.basename(x) for x in filter(
            os.path.isdir, glob.glob(os.path.join(path, '*')))]
    
    0 讨论(0)
  • 2020-11-22 08:38

    Lot of nice answers out there but if you came here looking for a simple way to get list of all files or folders at once. You can take advantage of the os offered find on linux and mac which and is much faster than os.walk

    import os
    all_files_list = os.popen("find path/to/my_base_folder -type f").read().splitlines()
    all_sub_directories_list = os.popen("find path/to/my_base_folder -type d").read().splitlines()
    

    OR

    import os
    
    def get_files(path):
        all_files_list = os.popen(f"find {path} -type f").read().splitlines()
        return all_files_list
    
    def get_sub_folders(path):
        all_sub_directories_list = os.popen(f"find {path} -type d").read().splitlines()
        return all_sub_directories_list
    
    0 讨论(0)
提交回复
热议问题