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

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

问题描述

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

/folderA/folderB/folderC/folderD/

我怎样才能获得 folderD 部分?

解决方案

使用 os.path.normpath,然后是 os.path.basename:

<预><代码>>>>os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))'文件夹D'

第一个去掉任何尾部斜杠,第二个给你路径的最后一部分.仅使用 basename 给出最后一个斜杠后的所有内容,在本例中为 ''.

In Python, suppose I have a path like this:

/folderA/folderB/folderC/folderD/

How can I get just the folderD part?

解决方案

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

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

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天全站免登陆