How to get parent folder name of current 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'

Tags:

Python