I have two folders. Call them A and B.
A is populated with python code. Among them, function1.py.
B contains data, and a soft link (created using ln -s) to A/function1.py.
When I execute B/function1.py, pwd points to A, not B. How do I fix this?
1 Answer 1
Removing the script name from the __file__
Solution 1: path: str = os.path.dirname(__file__)
Solution 2: path: str = os.path.sep.join(__file__.split(os.path.sep)[:-1])
Solution 1 works by just getting the parent directory of the current script path. Solution 2 works by removing the script name from the full script path. Also, if you're using windows, replacing os.altsep with os.sep in __file__ may be required!
Resolving softlinks in your path:
Check out the os.path package, there you will probably find a function for that.
I am not really sure, but maybe try using os.path.realpath? If not, try os.path.abspath.
note
I didn't test any of this sadly cuz i am lazy, so it may not work!
pwdLinux command from withinfunction1.py? When you executeB/function1.py, you're actually executingA/function1.py, sinceB/function1.pyis just a symbolic link.pwd) is the directory where you call the script from, not the path to the script. If you are in/var/runand you call/B/function1.py, the working directory is/var/run. The working directory doesn't change if the script is a soft link. You can change your current working directory withcd ../Bbefore you run the script or you can change the working directory inside the script withos.chdir(path).