In Python, suppose I have a path like this:
/folderA/folderB/folderC/folderD/
How can I get just the folderD
part?
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.
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.
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 ''
.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With