0

I am having issue in fetching the correct path of the file using os.path.abspath(__file__).

File: Assessment.py

Actual path: /Users/akshay.dubey/xyz/Assessment.py

python version - 3.7.1

When I am running the script on terminal it shows me a different path, such as /Users/akshay.dubey/xyz/assignment/dataset/Assessment.py and there is no file Assessment.py there.

Just to add, I have code to change current working directory to /Users/akshay.dubey/xyz/assignment/dataset but ideally that should not cause the value for os.path.abspath(__file__) to change. And when I remove the cwd it shows the correct value.

Code to reproduce:

import os

print(os.path.abspath(os.path.realpath(__file__)))
os.chdir('assignment/dataset1/')
print(os.path.abspath(os.path.realpath(__file__)))

O/P:

>>python untitled1.py
/Users/akshay.dubey/xyz/untitled1.py
/Users/akshay.dubey/xyz/assignment/dataset1/untitled1.py
tripleee
  • 175,061
  • 34
  • 275
  • 318
AKD
  • 13
  • 3
  • is there a symlink to the file? what does `os.path.abspath(os.path.realpath(__file__))` produce? (see [`os.path.realpath`](https://docs.python.org/3/library/os.path.html#os.path.realpath)) – hiro protagonist Feb 07 '20 at 11:46
  • [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Shubham Sharma Feb 07 '20 at 11:47
  • os.path.abspath(os.path.realpath(__file__)) is also giving the wrong path. I don't see any symlink. Do you know command to see if symlink exists. what if I moved the file from that location to new one, will it create symlink? – AKD Feb 07 '20 at 11:51
  • What exactly `__file__` gives you depends on a lot of factors, in your case it probably just gives "Assessment.py". From the string "Assessment.py" there's *no way* to construct an absolute path in any meaningful way, especially if the CWD doesn't happen to match the directory the file is in. See the duplicate for robust solutions… – deceze Feb 07 '20 at 11:54
  • Well, I just created a new file and wrote these 4 lines there. It is giving wrong path. import os print(os.path.abspath(os.path.realpath(__file__))) os.chdir('assignment/dataset1/') print(os.path.abspath(os.path.realpath(__file__))) Output: >>python untitled1.py /Users/akshay.dubey/xyz/untitled1.py /Users/akshay.dubey/xyz/assignment/dataset1/untitled1.py – AKD Feb 07 '20 at 11:58
  • Your code would be convincing if it was reproducible; but I can't repro with the program you posted. Again, do you have some symlinks in there? Does removing the `os.path.realpath()` call reveal a different path? – tripleee Feb 07 '20 at 12:20

0 Answers0