Home > Mobile >  How to extract a path if it contains a folder
How to extract a path if it contains a folder

Time:08-24

Lets say some paths like these:

C:/Test/path_i_need/test2/test3/test4
C:/Test/test2/path_i_need/test3
C:/Test/test2/test3/path_i_need/test4

How I can extract the path that i need in each of the scenarios using python, for example:

C:/Test/path_i_need
C:/Test/test2/path_i_need
C:/Test/test2/test3/path_i_need

So basically i don't know how many sub folder are before the path_i_need or after it, I only need that path, i dont care whats after.

CodePudding user response:

Try this, without using os module or any imports:

paths = """
C:/Test/path_i_need/test2/test3/test4
C:/Test/test2/path_i_need/test3
C:/Test/test2/test3/path_i_need/test4
""".strip().split('\n')

need_this_path = 'path_i_need'

len_that_which_i_need = len(need_this_path)

extracted_paths = [p[:p.index(need_this_path)   len_that_which_i_need] for p in paths]
print(*extracted_paths, sep='\n')

Outputs:

C:/Test/path_i_need
C:/Test/test2/path_i_need
C:/Test/test2/test3/path_i_need

CodePudding user response:

You could do a DFS (depth-first search) from the root directory until you find all the paths you're looking for:

from os import listdir, path

ROOT_DIR = "./example"
FLAG = "example1"

found_dirs = []

def find_dirs(p):
  subdirs = listdir(p)
  for subdir in subdirs:
    curdir = path.join(p, subdir)
    if subdir == FLAG:
      found_dirs.append(curdir)
    elsif path.isdir(curdir):
      find_dirs(curdir)

find_dirs(ROOT_DIR)
  • Related