I know there are functions for finding parent directory or path such as.
os.path.dirname(os.path.realpath(__file__))
'C:\Users\jahon\Desktop\Projects\CAA\Result\caa\project_folder'
Is there a function that just returns the parent folder name? In this case it should be project_folder
.
Using os.os. path. abspath() can be used to get the parent directory. This method is used to get the normalized version of the path.
bd command allows users to quickly go back to a parent directory in Linux instead of typing cd ../../.. repeatedly. You can list the contents of a given directory without mentioning the full path ls `bd Directory_Name` . It supports following other commands such as ls, ln, echo, zip, tar etc..
In the MS-DOS or Windows command line, the current working directory is displayed as the prompt. For example, if the prompt was "C:\Windows\System32>" the "System32" directory is the current directory, "Windows" is the parent directory, and "C:\" is the drive (root directory).
You can achieve this easily with os
import os
os.path.basename(os.getcwd())
You can get the last part of any path using basename
(from os.path
):
>>> from os.path import basename
>>> basename('/path/to/directory')
'directory'
Just to note, if your path ends with /
then the last part of the path is empty:
>>> basename('/path/to/directory/')
''
Yes, you can use PurePath.
PurePath(__file__).parent.name == 'parent_dir'
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