0

I want to go through a hirarchy-tree and check if I am at a specific directory (see picture). If this is true, I want to append this path (including the filenames in this path) to an array. I got stuck at the part where I want to check the current directory. Here is my code so far:

PATH = "../../data/"
paths = []

for path, dir, filenames in os.walk(PATH):
    if dir == "root/dir2/1":
        for filename in filenames:
            paths.append(os.path.join(path, filename))
        break

Hierarchy-tree

7
  • why loop over number folders and check for particular folder? Just try to access the folder - it will succeed or fail if the folder does not exist. Maybe I misunderstand your goal? Commented Dec 2, 2021 at 14:34
  • Unrelated: dir is a built-in Python keyword and should not be used as a variable name. Commented Dec 2, 2021 at 14:35
  • The value you're calling dir is a list of subdirectory names - dirnames might be a better name for it. It will never be equal to any string. path is what tells you what directory is currently being walked, but I'm pretty sure it will never be equal to your string (it will be whatever path you passed to os.walk(), with additional directories added onto the end). Note that if you're only interested in files in a single directory, you should just use os.listdir() on that directory; os.walk() is inappropriate. Commented Dec 2, 2021 at 14:36
  • How about glob.glob('**/1', recursive=True)? Commented Dec 2, 2021 at 14:39
  • @buran the thing is, that each folder exists. I just want to find a specific folder. Commented Dec 2, 2021 at 15:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.