Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

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())

The standard pythonic way of denoting that "this is a thing I don't want" is to call it _ - as in:

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

Note that this doesn't do anything special. The object is being created inside os.split(), and it's still being returned and given the name _ - but this does make it clear to people reading your code that you don't care about that particular element.

As well as being a signal to other people, most IDEs and code validators will understand that the variable called _ is to be ignored, and they won't do things like warn you about it never being used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top