36

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

U11-Forward
  • 41,703
  • 9
  • 50
  • 73
spen123
  • 2,934
  • 10
  • 34
  • 50
  • The answer is here. [link](http://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory) – GAVD Jul 07 '15 at 02:06

3 Answers3

51
>>> import os
>>> os.getcwd()
Joe T. Boka
  • 5,979
  • 6
  • 24
  • 46
  • 6
    That would return `/home/user/test/`, not `test`. –  Jul 07 '15 at 02:03
  • 6
    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/`) – bytesized Feb 06 '17 at 18:46
  • 2
    @bytesized 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. – greatwolf Feb 25 '17 at 06:01
  • 2
    @greatwolf 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. – bytesized Feb 25 '17 at 18:52
  • 2
    this just returns current working directory. So whichever location you're calling your python script from is going to be returned. @greatwolf 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 '/' – geekidharsh Nov 14 '17 at 21:57
  • it is amazing how many wrong answers like this are floating around. op didn't ask for cwd – eric Feb 02 '21 at 04:06
51
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
bytesized
  • 1,420
  • 11
  • 22
  • 8
    +1 `os.path.basename(os.getcwd())` also works if you care only for the directory you run the script from. – Magicsowon Mar 24 '17 at 10:49
-2

Just write

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

Hope this helps...

Subham Debnath
  • 531
  • 5
  • 7