Reputation: 5942
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
.
Upvotes: 25
Views: 36597
Reputation: 241
You can use split and os.path.sep to get the list of path elements and then call the last element of the list:
import os
path = 'C:\\Users\\jahon\\Desktop\\Projects\\CAA\\Result\\caa\\project_folder'
if path.split(os.path.sep)[-1]:
parent_folder = path.split(os.path.sep)[-1] # if no backslashes at the end
else:
parent_folder = path.split(os.path.sep)[-2] # with backslashes at the end
Upvotes: 0
Reputation: 1602
Yes, you can use PurePath.
PurePath(__file__).parent.name == 'parent_dir'
Upvotes: 10
Reputation: 24133
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/')
''
Upvotes: 21
Reputation: 2448
You can achieve this easily with os
import os
os.path.basename(os.getcwd())
Upvotes: 24