File: mergeall-products/unzipped/test/test-path-normalization-3.3/prototype-recoding-oct22/py-split-join--tools.txt

# Demo Python's stdlib tools in this domain



Stdlib joins may be too "smart"

>>> import ntpath as np
>>> p1 = r'C:\Users\lutz\file.txt'
>>> p2 = r'C:Users\lutz\file.txt'
>>>
>>> p1.split(np.sep)
['C:', 'Users', 'lutz', 'file.txt']
>>> p2.split(np.sep)
['C:Users', 'lutz', 'file.txt']
>>>
>>> np.join(*p1.split(np.sep))
'C:Users\\lutz\\file.txt'
>>> np.join(*p2.split(np.sep))
'C:Users\\lutz\\file.txt'

>>> import posixpath as pp
>>> p1 = '/Users/me/file.txt'
>>> p2 = 'Users/me/file.txt'
>>>
>>> p1.split(pp.sep)
['', 'Users', 'me', 'file.txt']
>>> p2.split(pp.sep)
['Users', 'me', 'file.txt']
>>>
>>> pp.join(*p1.split(pp.sep))
'Users/me/file.txt'
>>> pp.join(*p2.split(pp.sep))
'Users/me/file.txt'



Better? - manual sep splits/joins offer more control

>>> p1 = r'C:\Users\lutz\file.txt'
>>> p2 = r'C:Users\lutz\file.txt'
>>>
>>> np.sep.join(p1.split(np.sep))
'C:\\Users\\lutz\\file.txt'
>>> np.sep.join(p2.split(np.sep))
'C:Users\\lutz\\file.txt'
>>>
>>> p1 = '/Users/me/file.txt'
>>> p2 = 'Users/me/file.txt'
>>>
>>> pp.sep.join(p1.split(pp.sep))
'/Users/me/file.txt'
>>> pp.sep.join(p2.split(pp.sep))
'Users/me/file.txt'



Moot - just extracts last component, not a full path split

>>> np.split(p1)
('C:\\Users\\lutz', 'file.txt')
>>> np.split(p2)
('C:Users\\lutz', 'file.txt')

>>> pp.split(p1)
('/Users/me', 'file.txt')
>>> pp.split(p2)
('Users/me', 'file.txt')



[Home page] Books Code Blog Python Author Train Find ©M.Lutz