Search code examples
pythonpathpackagelocal

How to set a local variable path into a python package?


I try to build a python package like that :

myPackage/
    myPackage.py
    conf/
        conf1.conf
        conf2.conf

When I build and install the package, all files are in the

/usr/local/lib/python3.8/dist-packages/myPackage

directory.

Fine.

BUT : In myPackage.py file I need to set a local variable referring to my conf1.conf file So I wrote :

path_conf1 = "conf/conf1.conf"
def myFunction(path_conf1):
    with open(path_conf1,"r") as f:
        # do something 

But path_conf1 is unknown, because Python try to find it where I launch the script, not inside the myPackage itself.

I tried a lot of Google Search but I don't find that specific case.

How to deal with that issue ?

Thanks


Solution

  • You need to tell python the full file path. One way of doing this is with the use of the os library.

    import os
    path = os.path.dirname(os.path.realpath(__file__))
    

    then you can add the end of you path on that. Something along the lines of

    path_conf1 = path + path_conf1