0

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?

humanica
  • 419
  • 1
  • 4
  • 6
  • `open("myConfig")` will not open "myConfig.py". These are two different file names. – DYZ Jan 31 '20 at 07:25
  • 1
    Does this answer your question? [Opening a file from an imported function](https://stackoverflow.com/questions/59994911/opening-a-file-from-an-imported-function) – thebjorn Jan 31 '20 at 07:31

1 Answers1

2

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.

Valentin M.
  • 520
  • 5
  • 19