Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."

Question:

Import pygame

pygame.init()

BG = pygame.image.load('_pycache_/test_bg.jpg')

def DrawGameWin():
    window.blit(BG,(0,0))

pygame.display.update()


DrawGameWin()
Asked By: user12144855

||

Answers:

The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python file.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. Alternatively, you can create an absolute file path.


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

import os

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

An alternative solution is to find the absolute path.
If the file is in an subfolder 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 relative filepath. 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
filePath = os.path.join(sourceFileDir, 'test_bg.jpg')
# filePath = os.path.join(sourceFileDir, '_pycache_/test_bg.jpg')

surface = pygame.image.load(filePath)

The same can be achieved with the pathlib module.
Change the working directory

import os, pathlib

os.chdir(pathlib.Path(__file__).resolve().parent)

or create an absolute filepath:

import pathlib

# [...]

filePath = pathlib.Path(__file__).resolve().parent / 'test_bg.jpg'
surface = pygame.image.load(filePath)
Answered By: Rabbid76

I’m not very good, but don’t you have to import it to function?

BG = pygame.image.load('_pycache_/test_bg.jpg')
def DrawGameWin(BG):
    window.blit(BG,(0,0))
DrawGameWin(BG)
Answered By: Filip Stefko
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.