get script directory name – Python

Question:

I know I can use this to get the full file path

os.path.dirname(os.path.realpath(__file__))

But I want just the name of the folder, my scrip is in. SO if I have my_script.py and it is located at

/home/user/test/my_script.py

I want to return “test” How could I do this?

Thanks

Asked By: spen123

||

Answers:

>>> import os
>>> os.getcwd()
Answered By: Joe T. Boka
import os
os.path.basename(os.path.dirname(os.path.realpath(__file__)))

Broken down:

currentFile = __file__  # May be 'my_script', or './my_script' or
                        # '/home/user/test/my_script.py' depending on exactly how
                        # the script was run/loaded.
realPath = os.path.realpath(currentFile)  # /home/user/test/my_script.py
dirPath = os.path.dirname(realPath)  # /home/user/test
dirName = os.path.basename(dirPath) # test
Answered By: bytesized

Just write

import os
import os.path
print( os.path.basename(os.getcwd()) )

Hope this helps…

Answered By: Subham Debnath
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.