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.

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
  • 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 http://stackoverflow.com/questions/2860153/how-do-i-get-the-parent-directory-in-python for how to get the parent folder on the condition you find the file, else continue going up. – Dhruv Ghulati Aug 08 '16 at 22:20
  • Also use `os.path.join` instead of manually sending in strings to functions – Dhruv Ghulati Aug 08 '16 at 22:24

1 Answers1

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"
Dhruv Ghulati
  • 2,976
  • 3
  • 35
  • 51