Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Last Path Component In a String

Tags:

python

string

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) 
like image 370
Brock Woolf Avatar asked Jul 23 '10 02:07

Brock Woolf


People also ask

What method removes the last element in a path?

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.

What is Nsurl?

An NSURL object is composed of two parts—a potentially nil base URL and a string that is resolved relative to the base URL. An NSURL object is considered absolute if its string part is fully resolved without a base; all other URLs are considered relative.


1 Answers

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.

like image 115
Daniel Kluev Avatar answered Sep 22 '22 15:09

Daniel Kluev