I have a python project in D:/program/python/test_project/. And in the directory have a entry script named 'start.py'.It uses relative path like './pictures/icons/pic.png' to index other files in this project.
Everything works fine until I use a CSharp Project to run the python project, and it throws the path Error Exception.I print 'os.path.abspath('.')' and it refers to path 'WPFApp\bin\Debug'.The WPF is the root directory of my CSharp project.
Why does it happen?Why the '.' that represent the current directory change?
When running an application through an IDE, you cannot really rely on the current directory (as opposed to when running by a .bat file for instance).
If you need resource files located in a relative way to your main script, you cannot use relative paths.
You can use __file__
which provides the full path name for the current python script, so
os.path.join(os.path.dirname(__file__),'pictures/icons/pic.png')
is the absolute path of your resource file, regardless of the current directory (which in general you cannot and should not rely on)
If for some reason you cannot change all your relative paths, you can change the current directory to the script directory at startup. Not the best solution, but it would probably work in this case:
os.chdir(os.path.abspath(os.path.dirname(__file__)))
(added abspath
as if __file__
returns a filename, dirname
returns an empty string and chdir
fails)