views:

92

answers:

5

Hi, guys,

I am using wxpython and python to develop a gui. If I use the wx.dirdialog to get the directory like this:

/folderA/folderB/folderC/folderD/

how can I get string "folderD"?

Thanks in advance.

+3  A: 

You could do

import os
os.path.basename('/folderA/folderB/folderC/folderD')

UPDATE1: This approach works in case you give it /folderA/folderB/folderC/folderD/xx.py. This gives xx.py as the basename. Which is not what you want I guess. So you could do this -

import os
path = "/folderA/folderB/folderC/folderD"
if os.path.isdir(path):
    dirname = os.path.basename(path)

UPDATE2: As lars pointed out, making changes so as to accomodate leading '\'.

from os.path import normpath, basename
basename(normpath('/folderA/folderB/folderC/folderD/'))
MovieYoda
This doesn't work if there are trailing slashes.
larsmans
In Python-think, os.path.basename(".../") correctly yields ''. Yes, I, too, find that sub-optimal. The ...basename(...normpath... solution below is canonical, though.
Cameron Laird
@lars yeah! just saw that in that case normalize the path first before feeding it to basename. os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
MovieYoda
+1 for honesty. I didn't post what went wrong in my previous Python scripts :)
larsmans
A: 
path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()
GSto
A: 
str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]
Andrew Sledge
he wants `folderD`. not `folderC`
MovieYoda
It gives "folderD" because the trailing slash makes the final item in the list be ""
neil
+7  A: 

Use os.path.normpath, then os.path.basename:

>>> print os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')
folderD

The first strips off any trailing slashes, the second gives you the last part of the path. Using only basename gives everything after the last slash, which in this case is ''.

larsmans
doesn't work. :D. You have reversed it. Should be: os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
mshsayem
You're right mshsayem, fixed it. I guess the natural order of actions clouded my programming reason :)
larsmans
A: 

A naive solution(Python 2.5.2+):

s="/path/to/any/folder/orfile"
desired_dir_or_file = s[s.rindex('/',0,-1)+1:-1] if s.endswith('/') else s[s.rindex('/')+1:]
mshsayem