I would like to write a Python function that is capable of taking a file path, like:
/abs/path/to/my/file/file.txt
And returning three string variables:
/abs– the root directory, plus the “top-most” directory in the pathfile– the “bottom-most” directory in the path; the parent offile.txtpath/to/my– everything in between the top- and bottom-most directories in the path
So something with the following pseudo-code:
def extract_path_segments(file):
absPath = get_abs_path(file)
top = substring(absPath, 0, str_post(absPath, "/", FIRST))
bottom = substring(absPath, 0, str_post(absPath, "/", LAST))
middle = str_diff(absPath, top, bottom)
return (top, middle, bottom)
Thanks in advance for any help here!
You are looking for
os.sep, together with variousos.pathmodule functions. Simply split the path by that character, then re-assemble the parts you want to use. Something like:This does not deal very well with Windows paths, where both
\and/are legal path separators. In that case you also have a drive letter, so you’d have to special-case that as well anyway.Output: