pythoncwd

How to import config file when calling script from somewhere in the system?


lets assume i have a Folder "myProject" with a script "mySkript.py" and a config file "myConfig.py".

When calling the script from within "myProject" i would do something like this:

with open("myConfig") as configurationRawData:
    # do something

Now lets assume i don't call the script from "myProject" folder but from "User/desktop". In this case, the open command will not actually find "myConfig". I am looking to make my skript use it's own path as root path and inherit this property to every other script it might call during execution. Any ideas?


Solution

  • There is a way to do it :

    import os
    
    config_file = os.path.join(os.path.dirname(__file__),"myConfig.py")
    
    with open(config_file) as configurationRawData:
        # do something
    

    __file__ is a internal python variable that represents the path to the current file (something like C:\Users\user\documents\scripts\mySkript.py for windows per example). It leads to the file itself, it does not depends on working directory.

    os.path.dirname(__file__) gives you the directory to the current file (C:\Users\user\documents\scripts\ for the example above).

    os.path.join() builds a path like your os likes it, so it will produce C:\Users\user\documents\scripts\myConfig.py for the example above.

    This will work whatever your operating system is (python handles it for you) and as long as your two files are in the same directory.