1

i have this path

c:\JAVA\eclipse\java-neon\eclipse\configuration\

i want to get back the last folder "configuration" or on

c:\JAVA\eclipse\java-neon\eclipse\configuration\S\D\CV\S\D\D\AAAAA

get "AAAAA"

i don't found this function on os.path thanks

JONI6543
  • 57
  • 1
  • 4
  • If you're careful to ensure there are no trailing slashes, [os.path.basename()](https://docs.python.org/2/library/os.path.html#os.path.basename) does what you're after. – asongtoruin Jun 02 '17 at 08:44
  • Possible duplicate of [How to get only the last part of a path in Python?](https://stackoverflow.com/questions/3925096/how-to-get-only-the-last-part-of-a-path-in-python) – McGrady Jun 02 '17 at 08:45

4 Answers4

0

Suppose you know you have a separator character sep, this should accomplish what you ask:

path.split(sep)[-1]

Where path is the str containing your path.

If you don't know what the separator is you can call

os.path.sep
gionni
  • 1,284
  • 1
  • 12
  • 32
0

You can use os.path.split to split according to path separator:

os.path.split(path)[-1]
Shai
  • 111,146
  • 38
  • 238
  • 371
0

please check the code

import os


def getFolderName(str):
    if(str.endswith("\\")):
        str = str[0:-2]
    return os.path.split(str)[-1]

print(getFolderName(r'c:\JAVA\eclipse\java-neon\eclipse\configuration\S\D\CV\S\D\D\AAAAA'))
youDaily
  • 1,372
  • 13
  • 21
0

if you're wanting to explore your paths try something like this

def explore(path):
    finalpaths = []
    for paths in os.listdir(path):
        nextpath = path + '/' + paths
        if os.path.isdir(nextpath):
            finalpaths.extend(explore(nextpath))
        else:
            finalpaths.append(path)
    return finalpaths

then if you run

set(explore(path)

you'll get a list of all folders that can be in that directory (the lowest folder down you can get)

this works for unix, you might need to change it to \ rather than / for windows

Tomos Williams
  • 1,988
  • 1
  • 13
  • 20