import os def pathsplit(pathstr, maxsplit=None): """split relative path into list""" path = [pathstr] while True: oldpath = path[:] path[:1] = list(os.path.split(path[0])) if path[0] == '': path = path[1:] elif path[1] == '': path = path[:1] + path[2:] if path == oldpath: return path if maxsplit is not None and len(path) > maxsplit: return path print(pathsplit('asd/asd\\asd\sad')) print(pathsplit('d:\stuff\morestuff\furtherdown\THEFILE.txt')) if __name__ == "__main__": tests = [ '', 'foo', 'foo/', 'foo\\', '/foo', '\\foo', 'foo/bar', 'foo/bar/', '/', 'c:', 'c:/', 'c:foo', 'c:/foo', 'c:/users/john/foo.txt', '/users/john/foo.txt', 'foo/bar/baz/loop', 'foo/bar/baz/', '//hostname/foo/bar.txt', ] for i, test in enumerate(tests): print("\nTest %d: %r" % (i, test)) a = pathsplit(test) print("%r" % a)