Hướng dẫn python list all subfolders

This below class would be able to get list of files, folder and all sub folder inside a given directory

import os
import json

class GetDirectoryList[]:
    def __init__[self, path]:
        self.main_path = path
        self.absolute_path = []
        self.relative_path = []


    def get_files_and_folders[self, resp, path]:
        all = os.listdir[path]
        resp["files"] = []
        for file_folder in all:
            if file_folder != "." and file_folder != "..":
                if os.path.isdir[path + "/" + file_folder]:
                    resp[file_folder] = {}
                    self.get_files_and_folders[resp=resp[file_folder], path= path + "/" + file_folder]
                else:
                    resp["files"].append[file_folder]
                    self.absolute_path.append[path.replace[self.main_path + "/", ""] + "/" + file_folder]
                    self.relative_path.append[path + "/" + file_folder]
        return resp, self.relative_path, self.absolute_path

    @property
    def get_all_files_folder[self]:
        self.resp = {self.main_path: {}}
        all = self.get_files_and_folders[self.resp[self.main_path], self.main_path]
        return all

if __name__ == '__main__':
    mylib = GetDirectoryList[path="sample_folder"]
    file_list = mylib.get_all_files_folder
    print [json.dumps[file_list]]

Whereas Sample Directory looks like

sample_folder/
    lib_a/
        lib_c/
            lib_e/
                __init__.py
                a.txt
            __init__.py
            b.txt
            c.txt
        lib_d/
            __init__.py
        __init__.py
        d.txt
    lib_b/
        __init__.py
        e.txt
    __init__.py

Result Obtained

[
  {
    "files": [
      "__init__.py"
    ],
    "lib_b": {
      "files": [
        "__init__.py",
        "e.txt"
      ]
    },
    "lib_a": {
      "files": [
        "__init__.py",
        "d.txt"
      ],
      "lib_c": {
        "files": [
          "__init__.py",
          "c.txt",
          "b.txt"
        ],
        "lib_e": {
          "files": [
            "__init__.py",
            "a.txt"
          ]
        }
      },
      "lib_d": {
        "files": [
          "__init__.py"
        ]
      }
    }
  },
  [
    "sample_folder/lib_b/__init__.py",
    "sample_folder/lib_b/e.txt",
    "sample_folder/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/a.txt",
    "sample_folder/lib_a/lib_c/__init__.py",
    "sample_folder/lib_a/lib_c/c.txt",
    "sample_folder/lib_a/lib_c/b.txt",
    "sample_folder/lib_a/lib_d/__init__.py",
    "sample_folder/lib_a/__init__.py",
    "sample_folder/lib_a/d.txt"
  ],
  [
    "lib_b/__init__.py",
    "lib_b/e.txt",
    "sample_folder/__init__.py",
    "lib_a/lib_c/lib_e/__init__.py",
    "lib_a/lib_c/lib_e/a.txt",
    "lib_a/lib_c/__init__.py",
    "lib_a/lib_c/c.txt",
    "lib_a/lib_c/b.txt",
    "lib_a/lib_d/__init__.py",
    "lib_a/__init__.py",
    "lib_a/d.txt"
  ]
]

This post will discuss how to list all subdirectories in a directory in Python.

1. Using os.listdir[] function

A simple solution to list all subdirectories in a directory is using the os.listdir[] function. However, this returns the list of all files and subdirectories in the root directory. You can filter the returned list using the os.path.isdir[] function to list only the subdirectories.

importos

rootdir='path/to/dir'

forfile inos.listdir[rootdir]:

    d=os.path.join[rootdir,file]

    ifos.path.isdir[d]:

        print[d]

Download Code

 
You can easily extend the solution to search within subdirectories as well, as shown below:

importos

deflistdirs[rootdir]:

    forfileinos.listdir[rootdir]:

        d=os.path.join[rootdir, file]

        if os.path.isdir[d]:

            print[d]

            listdirs[d]

rootdir ='path/to/dir'

listdirs[rootdir]

Download Code

2. Using os.scandir[] function

With Python 3.5, you can use the os.scandir[] function, which offers significantly better performance over os.listdir[]. It returns directory entries along with file attribute information. To filter the returned entries to exclude files, call the is_dir[] function, which returns True if the current entry is a directory or a symbolic link pointing to a directory.

importos

rootdir='path/to/dir'

forit inos.scandir[rootdir]:

    ifit.is_dir[]:

        print[it.path]

Download Code

 
You can easily make the above code recursive to enable search within subdirectories:

importos

deflistdirs[rootdir]:

    forit inos.scandir[rootdir]:

        ifit.is_dir[]:

            print[it.path]

            listdirs[it]

rootdir='path/to/dir'

listdirs[rootdir]

Download Code

3. Using pathlib module

You can also use the pathlib module with Python 3.4 to list all subdirectories in a directory. The idea is to call the Path.iterdir[] function, yielding path objects of the directory contents. You can filter the returned objects for directories or a symbolic link pointing to a directory, use the Path.is_dir[][] function.

frompathlib importPath

rootdir='path/to/dir'

forpath in Path[rootdir].iterdir[]:

    if path.is_dir[]:

        print[path]

Download Code

 
Here’s the recursive version, which also searches within the subdirectories:

frompathlib importPath

def listdirs[rootdir]:

    forpath in Path[rootdir].iterdir[]:

        ifpath.is_dir[]:

            print[path]

            listdirs[path]

rootdir='path/to/dir'

listdirs[rootdir]

Download Code

4. Using os.walk[] function

To search in subdirectories, consider using the os.walk[] function. It recursively yields a 3-tuple [dirpath, dirnames, filenames], where dirpath is the path to the current directory, dirnames is a list of the names of the subdirectories in the current directory and filenames lists the regular files in the current directory.

importos

rootdir='path/to/dir'

for rootdir,dirs,files in os.walk[rootdir]:

    forsubdir indirs:

        print[os.path.join[rootdir,subdir]]

Download Code

5. Using glob module

Finally, you can use the glob.glob function, which returns an iterator over the list of pathnames that match the specified pattern.

importglob

rootdir='path/to/dir'

forpath inglob.glob[f'{rootdir}/*/']:

    print[path]

Download Code

 
Python 3.5 extended support for recursive globs using ** to search subdirectories and symbolic links to directories.

importglob

rootdir='path/to/dir'

forpath inglob.glob[f'{rootdir}/*/**/', recursive=True]:

    print[path]

Download Code

That’s all about listing all subdirectories in a directory in Python.


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


Chủ Đề