Jack
Jack

Reputation: 13

Is there a way to load images without using the root file in pygame?

When I load images using pygame, I normally just use file locations such as: 'B:\Python\Images\image.png' but if I want this to be able to run on different computers without needing to edit the code every time, I would just want to go like to do 'image.png' instead. Is there a way to do this? Whenever I try to skip the B:\Python\' part, I get the error: "File Error: No file "image.png" found in working directory 'C:\WINDOWS\System32."

I've seen people use a file location such as: '../Images/image.png' instead but that didn't work (I may have done it wrong).

Upvotes: 1

Views: 256

Answers (1)

Rabbid76
Rabbid76

Reputation: 210998

You have to set the working directory. The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python script. The name and path of the python file can be retrieved with __file__. The current working directory can be set with os.chdir(path).
Put the following at the beginning of your main script to set the working directory to the same as the script's directory. This allows you to specify file paths relative to your main file:

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

Upvotes: 2

Related Questions