python - Is it expected behavior with os.path.join() -
example1 path2 starts '/' results /dir2/dir3/
(missing path1)
path1='/volumes/disk1/' path2='/dir2/dir3/' print os.path.join(path1,path2)
example2 path2 not start '/' results proper /volumes/disk1/dir2/dir3/
:
path1='/volumes/disk1/' path2='dir2/dir3/' print os.path.join(path1,path2)
question: thought purpose of os.path.join() allow avoid work of tedious work of verifying if it's mac, windows or linux file path: 1 command all. if have watch if path2
starts or not start '/' (or '\') ruins every hope had , brings ton of code... solution? don't want ugliness:
if path2 , path2.replace('\\','/')[1:] , path2.replace('\\','/').startswith('/'): path2=path2[1:]
in order work without hassle of checking separators have start without them or remove them before passing os.path.join()
. in code below, show 3 ways can (live ideone example play with).
import os print os.path.join('volumes', 'disk1', 'dir2', 'dir3')
split paths join path1 = '/volumes/disk1/' path2 = '/dir2/dir3/' import os # convert same above: # i.e., os.path.join('volumes', 'disk1', 'dir2', 'dir3') print os.path.join(*(path1.split(os.sep) + path2.split(os.sep)))
custum bring together function using above code, can write custom join()
works either single- or multi- path strings:
def join(*paths): import os homecoming os.path.join(*[part path in paths part in path.split(os.sep)]) path1 = '/volumes/disk1/' path2 = '/dir2/dir3/' print join(path1, path2)
output:
'volumes/disk1/dir2/dir3'
python
No comments:
Post a Comment