0

It reports a filenotfound error when I enter the following code:

background = pygame.image.load('Art/base_vision.jpg')

The report was No file 'Art/window_icon.png' found in working directory 'C:\Users\xxx'

However, the directory of the script is c:/Users/xxx/Desktop/Game/Pygame test, and all of the art used in the project is in c:/Users/xxx/Desktop/Game/Pygame test/Art. It will simply not take files in the folder "Art", instead it will only take what's in C:/Users/xxx.

This is a group project I'm sending to team members, so the script needs to use files in its folder instead on C:.

Red
  • 26,798
  • 7
  • 36
  • 58

3 Answers3

0

use

background = pygame.image.load("./Art/base_vision.jpg")

./ will let your program know that it is a relative path and use your current working directory

0

you need to tell python to use the path of the current script and join it with the image relative path.

import os
script_directory = os.path.dirname(__file__)
image_relative_path = 'Art\\base_vision.jpg'
background = pygame.image.load(os.path.join(script_directory , image_relative_path))

whenever you write __file__ in a script it will always have the absolute path of the file where this variable is.

if you don't specify the absolute path of the file C:\users\... then python will look for files relative to your current working directory, what is current working directory.

Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23
0

Python's built-in pathlib library deals with this issue nicely. Here is an example of how your script.py could look, given a folder structure like you describe

Game/
├─ Pygame test/
│  ├─ script.py
│  ├─ Art/
│  │  ├─ art.png
from pathlib import Path

import pygame

SCRIPT_PATH = Path(__file__).resolve() # get the path of the script
PYGAME_PATH = SCRIPT_PATH.parents[0] # parents gives a list of parent directories, get the first one
ART_PATH = PYGAME_PATH / "Art" # the division operator for Path objects concatenates a Path object with a string

background = pygame.image.load(ART_PATH / "art.png")

Most libraries will accept Path objects, but in case they don't, you can always cast them back to a string by calling the as_posix method PATH_OBJECT.as_posix().

Also note that you shouldn't ever use backslashes when dealing with paths. The backslash has a special meaning in Python as an escape character. Python is smart enough to interpret forward slashes correctly, even on Windows (but using Path objects is pretty much as cross-platform as you will get, and provides a bunch of convenience functions as well).

stressed
  • 328
  • 2
  • 7