austin
austin

Reputation: 13

How to find the path of a specific deep subdirectory with only the subdirectory's name?

I want to move a file into a subdirectory. The subdirectory is within several subdirectories. I have only the name of the parent directory and the name of the subdirectory that I want the file to go into. I do not know the subdirectories in-between the parent directory and destination subdirectory and need to find where that subdirectory is with its absolute path so I can then move the file into that subdirectory.

I have tried os.path.isdir() and os.path.exists() to search for my subdirectory, but the search does not seem to search into all subdirectories.

    import os

def find_dir(name, start):
    for root, dirs, files in os.walk("."):
        for d in dirs:
            if d == name:
                return os.path.abspath(os.path.join(root, d))

subdir_name = 'Shanahan,Austin-1234'
starting_dir = r'C:\Users\austin.shanahan\Desktop\PeopleTest'

print(find_dir(subdir_name, starting_dir))   # returns "None"  

***There is a subdirectory called Shanahan,Austin-1234 deep in the directory PeopleTest. There are two subdirectories in-between the directory PeopleTest and the subdirectory Shanahan,Austin-1234. I need to find Shanahan,Austin-1234 within all of that and output the absolute path.

Upvotes: 1

Views: 212

Answers (1)

tgikal
tgikal

Reputation: 1680

Something like this?

layout:

.
  -> dir1
         -> dir2
                -> first.last-0000

Code:

import os

def find_dir(name, start):
    for root, dirs, files in os.walk(start):
        for d in dirs:
            if d == name:
                return os.path.abspath(os.path.join(root, d))

subdir_name = 'first.last-0000'
starting_dir = 'C:/users/me/desktop/peopleTest'

print(find_dir(subdir_name, starting_dir))

Result:

C:\Users\me\Desktop\peopleTest\dir1\dir2\first.last-0000

Upvotes: 3

Related Questions