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!

Answer from John Crawford on Stack Overflow
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
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ pathlib.html
pathlib โ€” Object-oriented filesystem paths
Source code: Lib/pathlib/ This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which pro...
Discussions

How to split a dos path into its components in Python - Stack Overflow
There's no reasonable reason to attempt (...and fail, of course) to iteratively parse apart pathnames when simple string splitting succeeds with only a single line of code. 2015-12-11T04:18:29.997Z+00:00 ... In Python >=3.4 this has become much simpler. You can now use pathlib.Path.parts to ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Best way to break up long file path string into multiple lines to adhere to PEP8?
If that's the full path, and you must hardcode it, there isn't. Keep it the way it is. Put in a comment to exclude it from your linter's complaints. More on reddit.com
๐ŸŒ r/learnpython
16
1
July 21, 2023
Add os.path.splitroot() - Ideas - Discussions on Python.org
The longstanding os.path.splitdrive() function splits a path into a (drive, tail) pair. But in some cases more detail is wanted, specifically a (drive, root, tail) triad. The drive part has the same meaning as in splitโ€ฆ More on discuss.python.org
๐ŸŒ discuss.python.org
1
December 28, 2022
Is there a simple way to split a path by a wildcard?
If you have the path in string form, you could split by "/*, then take the first element. More on reddit.com
๐ŸŒ r/learnpython
12
2
November 21, 2020
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ os.path.html
os.path โ€” Common pathname manipulations
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split().
๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-os-path-split-method
os.path.split() method - Python - GeeksforGeeks
May 9, 2025 - It constructs a full path by concatenating various components while automatically inserting the appropriate path separator (/ for Unix-based systems and \ for Windows). ExamplePythonimport ... OS module in Python provides functions for interacting with the operating system.
Top answer
1 of 16
481

I would do

import os
path = os.path.normpath(path)
path.split(os.sep)

First normalize the path string into a proper string for the OS. Then os.sep must be safe to use as a delimiter in string function split.

2 of 16
230

I've been bitten loads of times by people writing their own path fiddling functions and getting it wrong. Spaces, slashes, backslashes, colons -- the possibilities for confusion are not endless, but mistakes are easily made anyway. So I'm a stickler for the use of os.path, and recommend it on that basis.

(However, the path to virtue is not the one most easily taken, and many people when finding this are tempted to take a slippery path straight to damnation. They won't realise until one day everything falls to pieces, and they -- or, more likely, somebody else -- has to work out why everything has gone wrong, and it turns out somebody made a filename that mixes slashes and backslashes -- and some person suggests that the answer is "not to do that". Don't be any of these people. Except for the one who mixed up slashes and backslashes -- you could be them if you like.)

You can get the drive and path+file like this:

drive, path_and_file = os.path.splitdrive(path)

Get the path and the file:

path, file = os.path.split(path_and_file)

Getting the individual folder names is not especially convenient, but it is the sort of honest middling discomfort that heightens the pleasure of later finding something that actually works well:

folders = []
while 1:
    path, folder = os.path.split(path)

    if folder != "":
        folders.append(folder)
    else:
        if path != "":
            folders.append(path)

        break

folders.reverse()

(This pops a "\" at the start of folders if the path was originally absolute. You could lose a bit of code if you didn't want that.)

๐ŸŒ
Amit Chaudhary
amitness.com โ€บ posts โ€บ pathlib-cheatsheet
Migrating from OS.PATH to PATHLIB Module in Python
December 29, 2019 - import os base_path = '/home/ubuntu/' filename = 'data.csv' os.path.join(base_path, filename) In pathlib, we can use the division operator to separate the paths elegantly.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ best way to break up long file path string into multiple lines to adhere to pep8?
r/learnpython on Reddit: Best way to break up long file path string into multiple lines to adhere to PEP8?
July 21, 2023 -

Hi All,

I have a file path string that's over 88 characters, what would be the best way to break this up so that it's on multiple lines? I want to meet PEP8 guidelines.

chrome_driver_path = r"C:\Users\someusername\OneDrive\Documents\MyGitRepository\Web\chromedriver_win32\chromedriver114.exe"
๐ŸŒ
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 - source: os_path_basename_dirname_split_splitext.py ยท You can concatenate with the + operator to return the original path string. Concatenate strings in Python (+ operator, join, etc.)
๐ŸŒ
Yager-research
yager-research.ca โ€บ 2023 โ€บ 11 โ€บ how-to-break-apart-python-pathlib-paths
How to break apart Python pathlib Paths? | Kevin G. Yager
Python pathlib is the modern way to handle file paths. But I always forget how to break apart a path into components (directory part, filename part, etc.).
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
Add os.path.splitroot() - Ideas - Discussions on Python.org
December 28, 2022 - The longstanding os.path.splitdrive() function splits a path into a (drive, tail) pair. But in some cases more detail is wanted, specifically a (drive, root, tail) triad. The drive part has the same meaning as in splitdrive() The root part is ...
๐ŸŒ
Astral
docs.astral.sh โ€บ ruff โ€บ rules โ€บ os-sep-split
os-sep-split (PTH206) | Ruff - Astral Docs
import os "path/to/file_name.txt".split(os.sep)[-1] "path/to/file_name.txt".split(os.sep)[-2] # Iterating over the path parts if any(part in blocklist for part in "my/file/path".split(os.sep)): ... ... from pathlib import Path Path("path/to/file_name.txt").name Path("path/to/file_name.txt").parent.name # Iterating over the path parts if any(part in blocklist for part in Path("my/file/path").parts): ... While using pathlib can improve the readability and type safety of your code, it can be less performant than working directly with strings, especially on older versions of Python.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ pathlib-module
Python's pathlib module - Python Morsels
November 18, 2024 - With the automatic normalization done by pathlib.Path objects, you'll never need to worry about issues with mixing and matching / and \ on Windows. Pretty much any sort of splitting or segment-modification operation you can imagine with a file path is relatively simple with pathlib.Path objects.
๐ŸŒ
Switowski
switowski.com โ€บ blog โ€บ pathlib
Pathlib for Path Manipulations - Sebastian Witowski
July 17, 2023 - The list of various tasks we can perform with pathlib can go on for much longer. Creating, deleting, reading, writing, finding, moving, copying, splitting, and whatever other operation you want to perform on a file path or a file itself - pathlib probably has a function for that.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-extract-a-part-of-the-file-path-a-directory-in-python
How to extract a part of the file path (a directory) in Python?
March 24, 2026 - import os file_path = "/home/user/documents/sample.txt" # Split the path into components parts = file_path.split(os.sep) print("Path parts:", parts) # Access specific parts (index 0 is empty for absolute paths starting with /) print("Root:", parts[1]) # home print("User:", parts[2]) # user print("Directory:", parts[3]) # documents print("File:", parts[4]) # sample.txt ยท Path parts: ['', 'home', 'user', 'documents', 'sample.txt'] Root: home User: user Directory: documents File: sample.txt ยท The pathlib module provides an object-oriented interface for working with file system paths.
๐ŸŒ
HCL GUVI
studytonight.com โ€บ python-howtos โ€บ how-to-get-the-last-part-of-the-path-in-python
HCL GUVI | Learn to code in your native language
February 15, 2021 - HCL GUVI's Data Science Program was just fantastic. It covered statistics, machine learning, data visualization, and Python within its curriculum.