Cristiam MJ
Cristiam MJ

Reputation: 17

In python, Is it possible to get the path of the invoked from the invoked file?

I want to invoke config.py from ./, but I want config.py to recognize the path where it is located ("./second/config.py")

I want to invoke config.py from "./" and I want config.py to recognize and read file.json, but I dont want to send any paths as argument, nor append "./second" to sys.path. Is there a piece of code that can allow config.py recognize its relative path, and in this way join this path to the json's filename and read it?

./
├── main.py
└── second
      ├── config.py
      └── file.json

I tried this on config.py

def test():
 print(pathlib.Path().absolute())
 print(os.getcwd())

However, it returns

./

and I am expecting it to return

/second/config.py

Upvotes: 0

Views: 494

Answers (1)

Lorenzo Paolin
Lorenzo Paolin

Reputation: 289

you can use this two os methods together

import os
full_path = os.path.dirname(__file__) + os.path.basename(__file__) 

Upvotes: 1

Related Questions