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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With