You can recursively os.path.split string
import os def parts(path): p,f = os.path.split(path) return parts(p) + [f] if f else [p]
Testing this for some path lines and reassembling the path with os.path.join
>>> for path in [ ... r'd:\stuff\morestuff\furtherdown\THEFILE.txt', ... '/path/to/file.txt', ... 'relative/path/to/file.txt', ... r'C:\path\to\file.txt', ... r'\\host\share\path\to\file.txt', ... ]: ... print parts(path), os.path.join(*parts(path)) ... ['d:\\', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt'] d:\stuff\morestuff\furtherdown\THEFILE.txt ['/', 'path', 'to', 'file.txt'] /path\to\file.txt ['', 'relative', 'path', 'to', 'file.txt'] relative\path\to\file.txt ['C:\\', 'path', 'to', 'file.txt'] C:\path\to\file.txt ['\\\\', 'host', 'share', 'path', 'to', 'file.txt'] \\host\share\path\to\file.txt
The first list item may need to be handled differently depending on how you want to deal with drive letters, UNC paths, and absolute and relative paths. Changing the last [p] to [os.path.splitdrive(p)] causes the problem to split the drive letter and directory root into a tuple.
import os def parts(path): p,f = os.path.split(path) return parts(p) + [f] if f else [os.path.splitdrive(p)] [('d:', '\\'), 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt'] [('', '/'), 'path', 'to', 'file.txt'] [('', ''), 'relative', 'path', 'to', 'file.txt'] [('C:', '\\'), 'path', 'to', 'file.txt'] [('', '\\\\'), 'host', 'share', 'path', 'to', 'file.txt']
Edit: I realized that this answer is very similar to the above user1556435 , I leave my answer as the processing of the drive component in the path is different.