views:

53

answers:

3

If I have a string that looks like either

./A/B/c.d

OR

.\A\B\c.d

How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.

This problem kinda boils down to: How do I get the last of a specific character in a string?

Basically, I want the path of a file without the file part of it.

+5  A: 

Normally os.path.dirname() is used for this.

Ignacio Vazquez-Abrams
All the rest of the answers were right, but yours was shortest. Thank you. :)
Clark Gaebel
+3  A: 

I believe you are looking for os.path.split. It splits the path into head and tail... tail being the file, head being the path up to the file.

smencer
+3  A: 
>>> p="./A/B/c.d"
>>> import os
>>> os.path.split(p)
('./A/B', 'c.d')
>>> os.path.split(p)[0]
'./A/B'
>>> os.path.dirname(p)
'./A/B'
>>> p.rsplit("/",1)[0]
'./A/B
ghostdog74