0

Get location of the .py source file has some ideas but for example accepted one

# in /a/b/c/d/e/f/file.py
import os
print(os.path.dirname(os.path.abspath(__file__)))
os.chdir("..")
print(os.path.dirname(os.path.abspath(__file__)))

will print

/home/reducing_activity/Desktop/tmp/a/b/c/d/e/f
/home/reducing_activity/Desktop/tmp/a/b/c/d/e

is there a method that will survive os.chdir?

I am running Ubuntu 20.04 Linux 5.4.0-90-lowlatency #101-Ubuntu SMP PREEMPT Fri Oct 15 20:57:56 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux (from uname -a, computer name snipped)

With Python 3.8.10 (according to python3 --version)

reducing activity
  • 1,985
  • 2
  • 36
  • 64
  • Possibly a typo in your example - you have the script in `/a/b/c/d/e` but you're saying it will print `/a/b/c/d/e/f`. Additionally, I don't observe the behaviour you described - I get the same path for both print statements. – Kemp Nov 16 '21 at 15:14
  • @Kemp Thanks fixed! What is you OS and python version? – reducing activity Nov 16 '21 at 15:25
  • Mine is Python 3.8 on Windows 10. I wouldn't expect the value of `__file__` to ever change though, regardless of platform, and it turns out it generally shouldn't... except sometimes it might? Looking around I found this answer: https://stackoverflow.com/a/23616783/3228591 – Kemp Nov 16 '21 at 15:31
  • It's possible that the only completely reliable answer is to save `os.path.abspath(__file__)` somewhere (probably somewhere global for convenience unless you only need it in one scope) before modifying your working directory at all. – Kemp Nov 16 '21 at 15:36
  • @Kemp That is my current solution but I am not sure is what I see is a bug, intended behavior or what. – reducing activity Nov 16 '21 at 15:37
  • 1
    Judging by https://stackoverflow.com/a/22866630/3228591 and some of the other discussion in the other answers it sounds like it's a deliberate optimisation that leads to some unintuitive outcomes. So not a bug as such, but also not entirely useful in cases like yours. – Kemp Nov 16 '21 at 15:42

0 Answers0