Stefan Papp
Stefan Papp

Reputation: 2255

connecting multiple strings to path in python with slashes

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?

Upvotes: 5

Views: 3184

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43276

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'
    

Upvotes: 2

Anton vBR
Anton vBR

Reputation: 18916

Isn't the whole thing about os.path to not specify any delimiters?

How about this?

import os

mr = "mapr"
cn = "12.12.12"
lp = ["data","dir"]
vin = "var"

os.path.join(mr, cn, *lp, vin)

Upvotes: 1

Related Questions