如何仅获取Python路径的最后一部分? [英] How to get only the last part of a path in Python?

查看:1084
本文介绍了如何仅获取Python路径的最后一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,假设我有一个这样的路径:

In Python, suppose I have a path like this:

/folderA/folderB/folderC/folderD/

我如何只获得folderD部分?

推荐答案

使用 ,然后 os.path.basename :

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

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

第一个删除所有的斜杠,第二个为您提供路径的最后一部分.仅使用basename会给出最后一个斜杠(在本例中为'')之后的所有内容.

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 ''.

这篇关于如何仅获取Python路径的最后一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆