¿Cómo obtener solo la última parte de una ruta en Python?


En Python, supongamos que tengo un camino como este:

/folderA/folderB/folderC/folderD/

¿Cómo puedo obtener solo la parte folderD?

Author: Michael Currie, 2010-10-13

7 answers

Uso os.path.normpath, entonces os.path.basename:

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

La primera elimina las barras finales, la segunda le da la última parte del camino. Usar solo basename da todo después de la última barra, que en este caso es ''.

 237
Author: Fred Foo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-29 13:03:18

Usted podría hacer

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

UPDATE1: Este enfoque funciona en caso de que le des /folderA/folderB/folderC/folderD/xx.py. Esto da xx.py como el nombre base. Que no es lo que quieres, supongo. Así que usted podría hacer esto -

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

UPDATE2: Como lars señaló, haciendo cambios para acomodar '/'al final.

>>> from os.path import normpath, basename
>>> basename(normpath('/folderA/folderB/folderC/folderD/'))
'folderD'
 14
Author: Srikar Appalaraju,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-26 14:58:44

Aquí está mi enfoque:

>>> import os
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/test.py'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD'))
folderC
 7
Author: Mike Mitterer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-03 10:40:35

Estaba buscando una solución para obtener el último nombre de carpeta donde se encuentra el archivo, solo usé dividir dos veces, para obtener la parte correcta. No es la pregunta, pero Google me transfirió aquí.

pathname = "/folderA/folderB/folderC/folderD/filename.py"
head, tail = os.path.split(os.path.split(pathname)[0])
print(head + "   "  + tail)
 6
Author: user1767754,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-26 20:12:26

Una solución ingenua (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:]
 1
Author: mshsayem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-13 16:37:40
path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()
 0
Author: GSto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-13 15:06:12
str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]
 0
Author: Andrew Sledge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-13 15:06:45