Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parent folder name of current directory?

Tags:

python

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.

like image 552
Harun ERGUL Avatar asked Mar 19 '17 21:03

Harun ERGUL


People also ask

How do I get the parent directory of a current directory?

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.

How do I find parent directory in Linux?

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..

What is current directory and parent directory?

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).


3 Answers

You can achieve this easily with os

import os
os.path.basename(os.getcwd())
like image 104
mdegis Avatar answered Oct 27 '22 08:10

mdegis


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/')
''
like image 25
Peter Wood Avatar answered Oct 27 '22 08:10

Peter Wood


Yes, you can use PurePath.

PurePath(__file__).parent.name == 'parent_dir'
like image 9
Tankobot Avatar answered Oct 27 '22 09:10

Tankobot