0

I'm trying to return the current folder path of a python script, here is what I have

#test.py
import os
THIS_FOLDER = os.path.dirname(os.path.abspath('__file__'))
print(THIS_FOLDER)

When I run this script, it returns the folder that I am in when running it in the command prompt, not the folder of the python script.. How can I return the folder of the current python file?

user@vm:~$ python -u dir/test.py
/home/user
user@vm:~$ cd dir
user@vm:~/dir$ python -u test.py
/home/user/dir
Adam12344
  • 1,043
  • 16
  • 33

1 Answers1

0

You need to remove the quotes around __file__

In your script os.path.abspath gets a string '__file__' and returns '/home/user/__file__' (same as ./__file__ on *nix).

os.path.dirname then just strips the filename at the end of the string so your working directory (./) is left.

Edit: You want the absolute path of the folder that contains the script (__file__)
That becomes: os.path.abspath(os.path.dirname(__file__))

Check out this answer for more information.

micke
  • 899
  • 9
  • 23