user2751530
user2751530

Reputation: 281

Getting the working directory if the script is a soft link

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?

Upvotes: -1

Views: 38

Answers (1)

Olafcio
Olafcio

Reputation: 6

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!

Upvotes: -2

Related Questions