1

I am somewhat new to programming, I don't like it that much but as it is school work I have to do it, good thing I find it interesting.

Here is my code, note I'm using VS code (some things are in french but that shouldn't affect anything):

import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space vaders")
fond = pygame.image.load (testingfield.png)

and I get:

Traceback (most recent call last):
  File "c:/Users/faver/Desktop/Space_Invaders-NSI/space_invaders_1.py", line 11, in <module>
    fond = pygame.image.load ('testingfield.png')
FileNotFoundError: No such file or directory.

the file is indeed in the folder, and if I put fond = pygame.image.load ((r'C:\Users\faver\Desktop\Space_Invaders-NSI\testingfield.png'))it works perfectly, the problem now is that it'd be hard to actually send it since the other person would lack the folders I place there.

I've also tried import os a = os.path.lexists("/Users/suyeon/Documents/pythonWorkspace/pygame_basic/character.png") print(a) and it returned false, so I'm pretty much confused, I'd appreciate help if possible ^^'

Kami
  • 21
  • 1
  • 4

1 Answers1

1

The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.

The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).

One solution is to change the working directory:

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

An alternative solution is to find the absolute path. If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the image filename. e.g.:

import pygame
import os

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))

# [...]

# join the filepath and the filename
fondImgPath = os.path.join(sourceFileDir, 'testingfield.png')

fond = pygame.image.load(fondImgPath)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174