I am trying to get the last folder name from a path that i store in a string.
e.g: Home/new_folder/test
result = test
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 '' . I initially thought rstrip('/') would be simpler but then quickly realised I'd have to use rstrip(os.
basename(). os. path. basename() - It returns the last part of the path.
To get the trailing name component of a path you should use basename! In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.
dirname() method in Python is used to get the directory name from the specified path. Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path.
Use basename
basename('Home/new_folder/test'); // output: test
As a side note to those who answered explode:
To get the trailing name component of a path you should use basename! In case your path is something like $str = "this/is/something/"
the end(explode($str));
combo will fail.
You can use basename() function:
$last = basename("Home/new_folder/test");
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