1

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).

Jack
  • 13
  • 3
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – jahantaila Apr 04 '22 at 00:33
  • Depending on how you run your code, the working directory may not be the same folder as your python file is in. – Starbuck5 Apr 04 '22 at 01:23
  • How will you distribute your source code and assets? I recommend [PyInstaller](https://pyinstaller.readthedocs.io/en/stable/usage.html). This [question](https://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile) will be helpful. – import random Apr 04 '22 at 01:50
  • You can also set image sources through a configuration file or through environment variables. – RufusVS Apr 04 '22 at 05:08

1 Answers1

2

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__)))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174