Skip to content
Advertisement

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

JavaScript

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

JavaScript

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

JavaScript

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

JavaScript

or create an absolute filepath:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement