且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Python 中只获取路径的最后一部分?

更新时间:2023-02-23 13:38:48

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