Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function to extract multiple segments of a file path

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 path
  • file - the "bottom-most" directory in the path; the parent of file.txt
  • path/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!

like image 646
IAmYourFaja Avatar asked Nov 06 '25 19:11

IAmYourFaja


1 Answers

You are looking for os.sep, together with various os.path module functions. Simply split the path by that character, then re-assemble the parts you want to use. Something like:

import os

def extract_path_segments(path, sep=os.sep):
    path, filename = os.path.split(os.path.abspath(path))
    bottom, rest = path[1:].split(sep, 1)
    bottom = sep + bottom
    middle, top = os.path.split(rest)
    return (bottom, middle, top)

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:

>>> extract_path_segments('/abs/path/to/my/file/file.txt')
('/abs', 'path/to/my', 'file')
like image 93
Martijn Pieters Avatar answered Nov 09 '25 13:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!