Home > Software engineering >  Pygame Error : FileNotFoundError: No such file or directory
Pygame Error : FileNotFoundError: No such file or directory

Time:01-27

I'm new to programming and just following the steps provided online to make a small game in pygame to learn.

I recently have a problem when I wanted to add an image.

Here is my code.

    #sprite
from turtle import Screen
import pygame
import random
import os 

WIDTH=500
HEIGHT=600
#遊戲初始化 and 創建視窗
pygame.init()
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("spacegame")
background_img=pygame.image.load(os.path.join("img","background.png")).convert()
screen.blit(background_img,(0,0))

The trouble come when I run it, and they say :

    Traceback (most recent call last):
  File "d:\python\test.py", line 13, in <module>
    background_img=pygame.image.load(os.path.join("img","background.png")).convert()
FileNotFoundError: No file 'img\background.png' found in working directory 'D:\img'.
PS D:\img>

CodePudding user response:

You are already in the 'img' directory.

So you can use the following line to get the image:

background_img=pygame.image.load("background.png").convert()

CodePudding user response:

It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. A 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 file can be retrieved with __file__. The current working directory can be get by os.getcwd() and can be changed with os.chdir(path).
Put the following at the beginning of your code to set the working directory to the same as the script's directory:

import os

os.chdir(os.path.dirname(os.path.abspath(__file__)))
  •  Tags:  
  • Related