Remove Last Path Component In a String

Question:

I have a path:

myPath = "C:UsersmyFile.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)
Asked By: Brock Woolf

||

Answers:

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

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

Like this.

Answered By: Daniel Kluev

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'
Answered By: thefourtheye

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

>>> import pathlib
>>> path = pathlib.Path(r"C:UsersmyFile.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)

Other useful attributes/methods are:

path.name
>> "myFile.txt"
path.stem
>> "myFile"
path.parts
>> ("C:\", "Users", "myFile.txt")
path.with_suffix(".csv")
>> "myFile.csv"
path.iterdir()
>> #iterates over all files/directories in path location
path.isdir()
>> #tells you if path is file or directory
Answered By: johnDanger

While it is true that you should not maybe manipulate paths directly, and should use os.path module, sometimes, you may have your path as a string (for example, if your path was inside a text document, xml, etc.).

In such a situation, it might be safe and maybe even convenient to use string operations (as I found in my use case).

An example (assuming you have read your path from a text file, xml, etc. to a variable called path):

directory = "/".join(list(path.split('/')[0:-1])) 

The path is split with " / " as a seperator, sliced to remove the last item in the list, in OPs case "myFile.txt", and joined back with " / " as a seperator.

This will give the path with the file name removed.

OP had the path

myPath = "C:UsersmyFile.txt"

He will have

"C:Users"
Answered By: praveen nellihela
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.