Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute path of caller file

Tags:

python

Say I have two files in different directories: 1.py (say, in C:/FIRST_FOLDER/1.py) and 2.py (say, in C:/SECOND_FOLDER/2.py).

The file 1.py imports 2.py (using sys.path.insert(0, #path_of_2.py) followed, obviously, by import 2) and calls one of the functions in 2.py, the function it calls needs to know the absolute path of 1.py (it looks for a file in that same directory).

I know there's inspect.stack()[1] but this only returns the file name and not the path.

Any idea on how to implement this?

like image 217
Jonathan Avatar asked May 31 '16 13:05

Jonathan


1 Answers

import inspect
import os

abs_path = os.path.abspath((inspect.stack()[0])[1])
directory_of_1py = os.path.dirname(abs_path)

for more information on the module os.path

like image 127
gaganso Avatar answered Oct 05 '22 06:10

gaganso