KingCraft125
KingCraft125

Reputation: 23

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?

Upvotes: 2

Views: 48

Answers (1)

Kevin Müller
Kevin Müller

Reputation: 770

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

Upvotes: 2

Related Questions