get script directory name - Python [duplicate]
Asked Answered
M

3

38

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

Mohican answered 7/7, 2015 at 1:59 Comment(1)
The answer is here. linkNikolos
E
55
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
Encephalography answered 7/7, 2015 at 2:3 Comment(1)
+1 os.path.basename(os.getcwd()) also works if you care only for the directory you run the script from.Advert
R
50
>>> import os
>>> os.getcwd()
Rudderpost answered 7/7, 2015 at 2:2 Comment(6)
That would return /home/user/test/, not test.Dogtooth
Actually, if you were to call your script from another directory (cd /home/user; python test/my_script.py) it will not even return that. It will return the directory that you are in (in the example: /home/user/)Encephalography
@Encephalography But the OP did ask to get current working directory which means the current directory that you are in when you ran the interpreter. So os.getcwd does exactly that.Majesty
@Majesty To quote the OP, "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'". Although the title of the question is "get current directory", that is not what the OP wanted.Encephalography
this just returns current working directory. So whichever location you're calling your python script from is going to be returned. @Majesty so yes, cwd() doesn't solve the issue because OP just wanted first level path of the parent directory and not everything starting all the way from root aka '/'Alsup
it is amazing how many wrong answers like this are floating around. op didn't ask for cwdEmileeemili
B
-3

Just write

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

Hope this helps...

Bukharin answered 26/4, 2018 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.