maboesanman
maboesanman

Reputation: 407

Python find all subdirectories which contain a .txt file

I've got a directory which can have many folders within other folders, and txt files in them. I'd like to return a list of all directories which contain at least one .txt file.

I was attempting the following recursive approach, but it's not working:

def getDirectoryList(dir):
    directoryList = []

    # return nothing if dir is a file
    if not os.path.isdir(dir):
        return []

    # add dir to directorylist if it contains .txt files
    if len([file for file in os.listdir(dir) if file.endswith('.txt')])>0:
        directoryList.append(dir)
    for d in os.listdir(dir):
        for x in getDirectoryList(d):
            directoryList.append[x]

    return directoryList

Upvotes: 3

Views: 3861

Answers (1)

maboesanman
maboesanman

Reputation: 407

def getDirectoryList(path):
    directoryList = []

    #return nothing if path is a file
    if os.path.isfile(path):
        return []

    #add dir to directorylist if it contains .txt files
    if len([f for f in os.listdir(path) if f.endswith('.txt')])>0:
        directoryList.append(path)

    for d in os.listdir(path):
        new_path = os.path.join(path, d)
        if os.path.isdir(new_path):
            directoryList += getDirectoryList(new_path)

    return directoryList

here is the code that worked. the important differences are the if "os.path.isdir(os.path.join(path, d)):" check and the addition of path and d before recursive calls, because os.listdir() gives names, not paths

Upvotes: 6

Related Questions