Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only the last part of a path in Python?

In Python, suppose I have a path like this:

/folderA/folderB/folderC/folderD/ 

How can I get just the folderD part?

like image 380
pepero Avatar asked Oct 13 '10 15:10

pepero


People also ask

How do I get part of a path in Python?

The first and the easiest way to extract part of the file path in Python is to use the os. path. basename() function. This function returns the filename from the file path along with its extension.

How do I remove the last directory from a path in Python?

The path is split with " / " as a seperator, sliced to remove the last item in the list, in OPs case "myFile. txt", and joined back with " / " as a seperator. This will give the path with the file name removed.


2 Answers

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

like image 72
Fred Foo Avatar answered Oct 05 '22 10:10

Fred Foo


With python 3 you can use the pathlib module (pathlib.PurePath for example):

>>> import pathlib  >>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/') >>> path.name 'folderD' 

If you want the last folder name where a file is located:

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/file.py') >>> path.parent.name 'folderD' 
like image 28
jinnlao Avatar answered Oct 05 '22 10:10

jinnlao