How to get the parent folder name of the current directory?

I know that there are functions for finding the parent directory or path, for example.

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 name of the parent folder? In this case, it should be project_folder .

+5
source share
3 answers

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 note that if your path ends with / , then the last part of the path is empty:

 >>> basename('/path/to/directory/') '' 
+3
source

You can easily achieve this with os

 import os os.path.basename(os.getcwd()) 
+8
source

Yes, you can use PurePath .

 PurePath(__file__).parent.name == 'parent_dir' 
+4
source

Source: https://habr.com/ru/post/1265684/


All Articles