Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connecting multiple strings to path in python with slashes

Tags:

python

I try to concatenate the following strings to a path

mr = "/mapr"
cn = "12.12.12"
lp = "/data/dir/"
vin = "var"
os.path.join(mr, cn, lp, vin)

leads to

'/data/dir/var'

To get to the desired outcome I need to remove the first forward slash in the variable lp

lp = "data/dir/"
os.path.join(mr, cn, lp, vin)

'/mapr/12.12.12/data/dir/var'

Is there a more elegant to do it as I do not want to parse all identifiers for a forwarding slash in the beginning?

like image 960
Stefan Papp Avatar asked Oct 29 '22 11:10

Stefan Papp


1 Answers

The solution here depends on the context: How much power do you want to give your users? How much do you trust them to input something sensible? Is the result you want to get a relative path or an absolute path?

  • Option 1: Power to the users

    Let the users do whatever they want and make it their own responsibility to get it right:

    result = os.path.join(mr, cn, lp, vin)
    # result: '/data/dir/var'
    

    This gives the users the maximum degree of control.

  • Option 2: Force everything to be relative

    If you want to force every individual segment to be a relative path, there's no way around stripping any leading path separators.

    seps = r'\/'  # backslash for windows, slash for all platforms
    fragments = [part.strip(seps) for part in [mr, cn, lp, vin]]
    result = os.path.join(*fragments)
    # result: 'mapr/12.12.12/data/dir/var'
    

    If you need the result to be an absolute path, join it with your root directory:

    seps = r'\/'
    root = '/var/log'
    fragments = [part.strip(seps) for part in [mr, cn, lp, vin]]
    result = os.path.join(root, *fragments)
    # result: '/var/log/mapr/12.12.12/data/dir/var'
    
like image 113
Aran-Fey Avatar answered Nov 13 '22 16:11

Aran-Fey