pythonpathfilepathmodule-path

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

Solution

  • you can use this two os methods together

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