Search code examples
pythonpython-3.xpython-importpython-os

Get directory of imported file


I have a file in a package I am making that uses os.getcwd() to return the directory of the file. For example:

# myfile1py

import os
def getfiledir():
    return os.getcwd()

The above code returns C:\Users\Someone\Python36-32\Lib\site-packages\, which is the correct directory of the file. When I import it, though, an issue occurs.

# myfile2.py

import myfile
print(myfile.getfiledir())

The above code is the code in myfile2.py. After importing myfile1.py, I ran the function getfiledir() and it returns the directory of myfile2.py (C:\Users\Someone\Documents) instead of the directory of the imported file (myfile1.py).

How do I get the code in myfile2.py return the directory of myfile1.py?

Keep in mind that I want the code that returns the directory to be in the imported file (myfile1.py), not the importer file.

Any help would be greatly appreciated.


Solution

  • With the os module. It's on the standard library.

    import os
    os.path.dirname(myfile.__file__)
    

    Further details: How to retrieve a module's path?