Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting just the current directory without the full path in python

Tags:

python

os.path

I apologize if this is a question that has already been resolved. I want to get the current directory when running a Python script or within Python. The following will return the full path including the current directory:

os.getcwd()

I can also get the path all the way up to the current directory:

os.path.dirname(os.getcwd())

Using os.path.split will return the same thing as the above, plus the current folder, but then I end up with an object I want:

(thing_I_dont_want, thing_I_want) = os.path.split(os.getcwd())

Is there a way I can get just the thing I want, the current folder, without creating any objects I don't want around? Alternately, is there something I can put in place of the variable thing_I_dont_wantthat will prevent it from being created (e.g. (*, thing_I_want))?

Thanks!

like image 467
trynthink Avatar asked Jul 07 '13 21:07

trynthink


3 Answers

Like this:

os.path.split(os.getcwd())[1]

Although os.path.split returns a tuple, you don't need to unpack it. You can simply select the item that you need and ignore the one that you don't need.

like image 127
David Heffernan Avatar answered Nov 10 '22 13:11

David Heffernan


Use os.path.split:

>>> os.path.split(os.getcwd())
('/home/user', 'py')
>>> os.path.split(os.getcwd())[-1]
'py'

help on os.path.split:

>>> print os.path.split.__doc__
Split a pathname.  Returns tuple "(head, tail)" where "tail" is
    everything after the final slash.  Either part may be empty.
like image 21
Ashwini Chaudhary Avatar answered Nov 10 '22 14:11

Ashwini Chaudhary


You could try this, though it's not safe (as all the given solutions) if the pathname ends with a / for some reason:

os.path.basename(os.getcwd())
like image 28
filmor Avatar answered Nov 10 '22 13:11

filmor