Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get script directory name - Python [duplicate]

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

like image 472
spen123 Avatar asked Jul 07 '15 01:07

spen123


2 Answers

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
like image 154
bytesized Avatar answered Oct 20 '22 18:10

bytesized


>>> import os
>>> os.getcwd()
like image 32
Joe T. Boka Avatar answered Oct 20 '22 20:10

Joe T. Boka