71
votes

I have a path:

myPath = "C:\Users\myFile.txt"

I would like to remove the end path so that the string only contains:

"C:\Users"

So far I am using split, but it just gives me a list, and im stuck at this point.

myPath = myPath.split(os.sep)
3

3 Answers

104
votes

You should not manipulate paths directly, there is os.path module for that.

>>> import os.path
>>> print os.path.dirname("C:\Users\myFile.txt")
C:\Users
>>> print os.path.dirname(os.path.dirname("C:\Users\myFile.txt"))
C:\

Like this.

32
votes

You can also use os.path.split, like this

>>> import os
>>> os.path.split('product/bin/client')
('product/bin', 'client')

It splits the path into two parts and returns them in a tuple. You can assign the values in variables and then use them, like this

>>> head, tail = os.path.split('product/bin/client')
>>> head
'product/bin'
>>> tail
'client'
9
votes

The current way to do this (Python > 3.4) is to use the pathlib module.

>>> import pathlib
>>> path = pathlib.Path(r"C:\Users\myFile.txt")
>>> path.parent
WindowsPath('C:/Users')   #if using a Windows OS

>>> print(path.parent)
C:\Users

This has the additional benefit of being cross platform as pathlib will make a path object suited for the current operating system (I am using Windows 10)