0

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.

5
  • you will definitely need to use the OS package Commented Aug 22, 2022 at 17:20
  • what criteria will dictate what paths you need? Commented Aug 22, 2022 at 17:20
  • 1
    so whats special about path_ineed? for ex. is it like the project root directory or something else? Commented Aug 22, 2022 at 17:23
  • Check out pathlib from the standard libraries. Path objects can be used for many path manipulations. Commented Aug 22, 2022 at 17:24
  • Are you literally looking for a path component called "path_i_need"? Commented Aug 22, 2022 at 17:26

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.