Search code examples
python-3.xsubdirectory

Finding folders in a directory (Python 3)


I am using the code below to search for all text files in a directory.

import os

numOfFiles=0
files=[]

dir_path = os.path.dirname(os.path.realpath(__file__))

for file in os.listdir(dir_path):
    if file.endswith(".txt"):
        files.append(file)
        print(os.path.join(dir_path, file))
        numOfFiles=numOfFiles+1

How would i find all sub-directories within the variable dir_path using my existing code?


Solution

  • You can check for isdir():

    import os
    
    numOfFiles=0
    files=[]
    
    dir_path = os.path.dirname(os.path.realpath(__file__))
    
    for file in os.listdir(dir_path):
        if file.endswith(".txt"):
            files.append(file)
            print(os.path.join(dir_path, file))
            numOfFiles=numOfFiles+1
        if os.path.isdir(file):
            # ...Do something