So I'm a novice to Python, and as predicted, I've run into an issue when trying to figure out a file's directory. In my IDE, when I run the code:
Import OS
print(os.path.abspath("background.png"))
It works fine. (Bear in mind, the picture is in the same directory as the Python code. I'm also aware that you can use the following:
print(os.path.abspath(r"OldBGs\background.png"))
This returns:
C:\Users\me\Desktop...few folders...\OldBGs\background.png
This is what I am currently working with. However, when I try to run my code without my IDE (I do this by right-clicking the code.py and then choosing open with Python 3.8), for some reason it outputs:
C:\WINDOWS\system32\OldBGs\backgroundold.png
This is a pain, although it works with my IDE, I need to ensure that it works no matter whoever runs my code (with/without an IDE).
One way to achieve this is to make all paths relative to the position of the script file itself.
You can get the path to the directory of the script by:
import os
SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
Then, you can define all paths relative to SCRIPT_DIRECTORY
. For example:
BACKGROUND_PICTURE_PATH = os.path.join(SCRIPT_DIRECTORY , "background.png")
This path is now no longer dependent on where the script was run from, but where the script file itself is located. This means it will be the same path whether or not you're in an IDE.