0

I start my python code file foo.py from directory home/a/b/.

The file foo.py is located at home/x/y/k.

Inside the file foo.py what can be the way to get path home/x/y/k.

I have used the functions os.getcwd() and os.path.realpath(), they all return home/a/b.

I will appreciate any help in the direction.

martineau
  • 119,623
  • 25
  • 170
  • 301
Abhi
  • 29
  • 2
  • 8
  • 1
    check out \__file__ see this https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do/9271617 – bravosierra99 Feb 26 '19 at 01:58
  • Your current working directory is the directory from where the file is being executed. You must execute the file from your home directory to get absolute location of your file. – 0xInfection Feb 26 '19 at 02:00
  • @InfectedDrake I understand this, however, i do not have the option to execute the file from the home directory. – Abhi Feb 26 '19 at 02:04
  • do you mean to change the path? you can use os.chdir(path) to change your current working directory inside python code. – taipei Feb 26 '19 at 02:09
  • @taipei, no I do not need to change the path. From the code, I require the path from where the file foo.py is located and not from where it is getting executed. – Abhi Feb 26 '19 at 02:11
  • `from pathlib import Path; script_directory = Path(__file__).parent` – alkasm Feb 26 '19 at 02:14

1 Answers1

1

Use os.path.abspath(__file__) inside the foo.py file. This way, you will always get the path of your foo.py, no matter from where you start the script.

Hiadore
  • 686
  • 3
  • 15
  • 1
    Yes, I use this on some of my code. You need to pass the `__file__` argument into abspath. `__file__` is always refer to the python file where it is declared. If you only need to get the directory, use `os.path.dirname(os.path.abspath(__file__))`. – Hiadore Feb 26 '19 at 03:42
  • I'd recommend linking to the relevant docs as well. Welcome to Stack Overflow! – alkasm Feb 26 '19 at 04:06
  • Thank you. I appreciate the help. It works for me. I can get the path where the file is located. – Abhi Feb 27 '19 at 00:05
  • Great! By the way, If you believe my answer is helpful, do not hesitate to make it as accepted answer. Thanks! – Hiadore Feb 27 '19 at 01:34