Relative file paths (like your 'config.xml'
) are always relative to the directory you're calling the python
executable. For instance:
D:\dev\projects\>python myapp.py
If myapp.py
imports something from god-only-knows where that's looking for a file named "childfolder/filename.ext"
, then it's actually looking for D:\dev\projects\childfolder\filename.ext
.
If you need your file path to be relative to the script that is looking for it, you need to make it an absolute path. The easiest way to do this is by using __file__
, which is a magical variable that contains the absolute path to the script that's running. You can use os.path
to do this by getting the directory name of __file__
(the directory your file lives in) then join
ing it with the config.xml name:
os.path.join(os.path.dirname(__file__), "config.xml")
but pathlib
makes this even easier.
# inside D:\dev\projects\myapp.py
configpath = pathlib.Path(__file__).with_name("config.xml")
assert configpath == pathlib.Path(r"D:\dev\projects\config.xml") # ta-da!