0

What's the most pythonic way of finding the child folder from a supplied path?

import os

def get_folder(f, h):
  pathList = f.split(os.sep)
  sourceList = h.split(os.sep)

  src = set(sourceList)
  folderList = [x for x in pathList if x not in src]

  return folderList[0]


print get_folder("C:\\temp\\folder1\\folder2\\file.txt", "C:\\temp") # "folder1" correct
print get_folder("C:\\temp\\folder1\\file.txt", "C:\\temp") # "folder1" correct
print get_folder("C:\\temp\\file.txt", "C:\\temp") # "file.txt" fail should be "temp"

In the example above I have a file.txt in "folder 2". The path "C:\temp" is supplied as the start point to look from.

I want to return the child folder from it; in the event that the file in question is in the source folder it should return the source folder.

2
  • You should use something like os.path.walk to walk through all the files iteratively in each branch of the path, and look at this answer stackoverflow.com/questions/2860153/… for how to get the parent folder on the condition you find the file, else continue going up. Commented Aug 8, 2016 at 22:20
  • Also use os.path.join instead of manually sending in strings to functions Commented Aug 8, 2016 at 22:24

1 Answer 1

1

Try this. I wasn't sure why you said folder1 is correct for the first example, isn't it folder2? I am also on a Mac so os.sep didn't work for me but you can adapt this.

import os

def get_folder(f, h):
    pathList = f.split("\\")

    previous = None

    for index, obj in enumerate(pathList):
        if obj == h:
            if index > 0:
                previous = pathList[index - 1]

    return previous


print get_folder("C:\\temp\\folder1\\folder2\\file.txt", "file.txt") # "folder2" correct
print get_folder("C:\\temp\\folder1\\file.txt", "file.txt") # "folder1" correct
print get_folder("C:\\temp\\file.txt", "file.txt") # "file.txt" fail should be "temp"
Sign up to request clarification or add additional context in comments.

Comments

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.