You can use os.sep

just

import os
path_string.split(os.sep)

For more info, look the doc

os.path.join(path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last. (This means that an empty last part will result in a path that ends with a separator.) Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

Answer from atupal on Stack Overflow
๐ŸŒ
O'Reilly
oreilly.com โ€บ library โ€บ view โ€บ python-cookbook โ€บ 0596001673 โ€บ ch04s16.html
Splitting a Path into All of Its Parts - Python Cookbook [Book]
July 19, 2002 - The os.path.split function splits a path into two parts: everything before the final slash and everything after it.
Authors: Alex MartelliDavid Ascher
Published: 2002
Pages: 608
Discussions

Split path in Python - Stack Overflow
How I could split this: C:\my_dir\repo\branch to: ['C:\my_dir', rest_part_of_string] where rest_part_of_string can be one string or could be splitted every \. I don't care about rest, i just want More on stackoverflow.com
๐ŸŒ stackoverflow.com
cross-platform splitting of path in python - Stack Overflow
Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Slash vs backslash to separate folders
but whenever I copy a file address in Windows it copies with the folders separated by backslashes You should use an appropriate type for file paths, such as pathlib or os.path (low level), which handles the directory separators for you. https://docs.python.org/3/library/pathlib.html More on reddit.com
๐ŸŒ r/learnpython
7
3
February 1, 2024
Standard python function to split paths? - Stack Overflow
NOTE: Please, don't code it for me. I already have a home-rolled function to do what I describe below. Is there a function in the standard Python library that will take an absolute path as argume... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ os.path.html
os.path โ€” Common pathname manipulations โ€” Python 3.15.2 documentation
Any of these items may be the empty string. In all cases, drive + root + tail will be the same as path. On POSIX systems, drive is always empty. The root may be empty (if path is relative), a single forward slash (if path is absolute), or two ...
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ python-split-by-slash
Python `.split` by Slash: A Comprehensive Guide - CodeRivers
February 22, 2026 - The .split method in Python is a built-in string method that divides a string into a list of substrings based on a specified delimiter. When the delimiter is a slash (/), it separates the string at each occurrence of the slash character. For example, consider the string path = "home/user/documents" ...
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ os.path.html
11.2. os.path โ€” Common pathname manipulations โ€” Python 3.4.10 documentation
June 16, 2019 - Changed in version 3.4: Added Windows support. ... Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Get the Filename, Directory, Extension from a Path String in Python | note.nkmk.me
May 8, 2023 - UNIX (including Mac) uses the slash /, while Windows uses the backslash \. You can get the separator in the OS running Python with os.sep or os.path.sep. print(os.sep) # / print(os.sep is os.path.sep) # True ยท source: os_path_basename_dirn...
๐ŸŒ
codestudy
codestudy.net โ€บ blog โ€บ splitting-path-strings-into-drive-path-and-file-name-parts
How to Split Path Strings into Drive, Path, and Filename in Python: A Beginner's Guide โ€” codestudy.net
Key Takeaway: A trailing slash tells os.path.split() that the path is a directory, so the "filename" component is empty. Python 3.4 introduced pathlib, an object-oriented alternative to os.path.
Find elsewhere
Top answer
1 of 8
83

Python 3.4 introduced a new module pathlib. pathlib.Path provides file system related methods, while pathlib.PurePath operates completely independent of the file system:

>>> from pathlib import PurePath
>>> path = "/foo/bar/baz/file"
>>> path_split = PurePath(path).parts
>>> path_split
('\\', 'foo', 'bar', 'baz', 'file')

You can use PosixPath and WindowsPath explicitly when desired:

>>> from pathlib import PureWindowsPath, PurePosixPath
>>> PureWindowsPath(path).parts
('\\', 'foo', 'bar', 'baz', 'file')
>>> PurePosixPath(path).parts
('/', 'foo', 'bar', 'baz', 'file')

And of course, it works with Windows paths as well:

>>> wpath = r"C:\foo\bar\baz\file"
>>> PurePath(wpath).parts
('C:\\', 'foo', 'bar', 'baz', 'file')
>>> PureWindowsPath(wpath).parts
('C:\\', 'foo', 'bar', 'baz', 'file')
>>> PurePosixPath(wpath).parts
('C:\\foo\\bar\\baz\\file',)
>>>
>>> wpath = r"C:\foo/bar/baz/file"
>>> PurePath(wpath).parts
('C:\\', 'foo', 'bar', 'baz', 'file')
>>> PureWindowsPath(wpath).parts
('C:\\', 'foo', 'bar', 'baz', 'file')
>>> PurePosixPath(wpath).parts
('C:\\foo', 'bar', 'baz', 'file')

Huzzah for Python devs constantly improving the language!

2 of 8
24

The OP specified "will work with Windows paths too". There are a few wrinkles with Windows paths.

Firstly, Windows has the concept of multiple drives, each with its own current working directory, and 'c:foo' and 'c:\\foo' are often not the same. Consequently it is a very good idea to separate out any drive designator first, using os.path.splitdrive(). Then reassembling the path (if required) can be done correctly by drive + os.path.join(*other_pieces)

Secondly, Windows paths can contain slashes or backslashes or a mixture. Consequently, using os.sep when parsing an unnormalised path is not useful.

More generally:

The results produced for 'foo' and 'foo/' should not be identical.

The loop termination condition seems to be best expressed as "os.path.split() treated its input as unsplittable".

Here's a suggested solution, with tests, including a comparison with @Spacedman's solution

import os.path

def os_path_split_asunder(path, debug=False):
    parts = []
    while True:
        newpath, tail = os.path.split(path)
        if debug: print repr(path), (newpath, tail)
        if newpath == path:
            assert not tail
            if path: parts.append(path)
            break
        parts.append(tail)
        path = newpath
    parts.reverse()
    return parts

def spacedman_parts(path):
    components = [] 
    while True:
        (path,tail) = os.path.split(path)
        if not tail:
            return components
        components.insert(0,tail)

if __name__ == "__main__":
    tests = [
        '',
        'foo',
        'foo/',
        'foo\\',
        '/foo',
        '\\foo',
        '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)
        drive, path = os.path.splitdrive(test)
        print 'drive, path', repr(drive), repr(path)
        a = os_path_split_asunder(path)
        b = spacedman_parts(path)
        print "a ... %r" % a
        print "b ... %r" % b
        print a == b

and here's the output (Python 2.7.1, Windows 7 Pro):

Test 0: ''
drive, path '' ''
a ... []
b ... []
True

Test 1: 'foo'
drive, path '' 'foo'
a ... ['foo']
b ... ['foo']
True

Test 2: 'foo/'
drive, path '' 'foo/'
a ... ['foo', '']
b ... []
False

Test 3: 'foo\\'
drive, path '' 'foo\\'
a ... ['foo', '']
b ... []
False

Test 4: '/foo'
drive, path '' '/foo'
a ... ['/', 'foo']
b ... ['foo']
False

Test 5: '\\foo'
drive, path '' '\\foo'
a ... ['\\', 'foo']
b ... ['foo']
False

Test 6: 'foo/bar'
drive, path '' 'foo/bar'
a ... ['foo', 'bar']
b ... ['foo', 'bar']
True

Test 7: '/'
drive, path '' '/'
a ... ['/']
b ... []
False

Test 8: 'c:'
drive, path 'c:' ''
a ... []
b ... []
True

Test 9: 'c:/'
drive, path 'c:' '/'
a ... ['/']
b ... []
False

Test 10: 'c:foo'
drive, path 'c:' 'foo'
a ... ['foo']
b ... ['foo']
True

Test 11: 'c:/foo'
drive, path 'c:' '/foo'
a ... ['/', 'foo']
b ... ['foo']
False

Test 12: 'c:/users/john/foo.txt'
drive, path 'c:' '/users/john/foo.txt'
a ... ['/', 'users', 'john', 'foo.txt']
b ... ['users', 'john', 'foo.txt']
False

Test 13: '/users/john/foo.txt'
drive, path '' '/users/john/foo.txt'
a ... ['/', 'users', 'john', 'foo.txt']
b ... ['users', 'john', 'foo.txt']
False

Test 14: 'foo/bar/baz/loop'
drive, path '' 'foo/bar/baz/loop'
a ... ['foo', 'bar', 'baz', 'loop']
b ... ['foo', 'bar', 'baz', 'loop']
True

Test 15: 'foo/bar/baz/'
drive, path '' 'foo/bar/baz/'
a ... ['foo', 'bar', 'baz', '']
b ... []
False

Test 16: '//hostname/foo/bar.txt'
drive, path '' '//hostname/foo/bar.txt'
a ... ['//', 'hostname', 'foo', 'bar.txt']
b ... ['hostname', 'foo', 'bar.txt']
False
๐ŸŒ
GitHub
bic-berkeley.github.io โ€บ psych-214-fall-2016 โ€บ path_manipulation.html
Making and breaking file paths in Python โ€” Functional MRI methods
>>> from os.path import abspath ... /Users/mb312/dev_trees/psych-214-fall-2016/relative/path/then_filename.txt ยท Use splitext to split a path into: the path + filename; and the file extension:...
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ os_path_split.htm
Python os.path.split() Method
The head contains everything leading up to that component, representing the directory part of the path. If the specified path ends with a slash (/), the directory part will be the path itself, and the file part will be an empty string.
๐ŸŒ
Real Python
realpython.com โ€บ python-split-string
How to Split a String in Python โ€“ Real Python
February 5, 2025 - Because path starts with a forward slash, .split() cuts the string right away and creates an empty string as the first element. There was nothing before the first occurrence of the separator after all.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 3 โ€บ os.path โ€บ index.html
os.path โ€” Platform-independent Manipulation of Filenames โ€” PyMOTW 3
March 18, 2018 - The basename() function returns a value equivalent to the second part of the split() value. ... import os.path PATHS = [ '/one/two/three', '/one/two/three/', '/', '.', '', ] for path in PATHS: print('{!r:>17} : {!r}'.format(path, os.path.basename(path))) The full path is stripped down to the last element, whether that refers to a file or directory. If the path ends in the directory separator (os.sep), the base portion is considered to be empty. $ python3 ospath_basename.py '/one/two/three' : 'three' '/one/two/three/' : '' '/' : '' '.' : '.' '' : ''
๐ŸŒ
michael harty
mharty3.github.io โ€บ til โ€บ python โ€บ path-parts-in-pathlib
Accessing the parts of a file path with Pathlib (python) - michael harty
October 30, 2023 - Pathlib is the module in Python (>3.4) for working with filesystem paths. It has a lot of useful methods. One useful set of methods are those to access the various parts of a path. Itโ€™s much easier and more reliable than trying to split strings on forward slashes or back slashes.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-4343.html
[split] Single slash syntax in file path
I am having a similar noob problem. Setup: I'm calling the python script with arguments from a different program through the command prompt (this other program does not offer full python integration) This other program collects a file path, turns it...