How to split a dos path into its components in Python

How to split a dos path into its components in Python

I would do

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

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.

Ive 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 Im 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 wont 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. Dont 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 != :
    elif path != :



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

How to split a dos path into its components in Python

In Python >=3.4 this has become much simpler. You can now use to get all the parts of a path.


>>> from pathlib import Path
>>> Path(C:/path/to/file.txt).parts
(C:\, path, to, file.txt)
>>> Path(rC:pathtofile.txt).parts
(C:\, path, to, file.txt)

On a Windows install of Python 3 this will assume that you are working with Windows paths, and on *nix it will assume that you are working with posix paths. This is usually what you want, but if it isnt you can use the classes pathlib.PurePosixPath or pathlib.PureWindowsPath as needed:

>>> from pathlib import PurePosixPath, PureWindowsPath
>>> PurePosixPath(/path/to/file.txt).parts
(/, path, to, file.txt)
>>> PureWindowsPath(rC:pathtofile.txt).parts
(C:\, path, to, file.txt)
>>> PureWindowsPath(r\hostsharepathtofile.txt).parts
(\\host\share\, path, to, file.txt)

There is also a backport to python 2 available: pathlib2

Leave a Reply

Your email address will not be published. Required fields are marked *