Skip to content
Advertisement

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

Import pygame

pygame.init()

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

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

pygame.display.update()


DrawGameWin()

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement