pygame.error “couldn’t open image.png” only in command prompt

The fact, that the file is in the same directory as the program doesn’t matter. If you don’t provide a path the program will look for the file in the working directory which might be a total different one.

If you want to use a specific directory add your path to the filename. A flexible approach would be to determine the path of the current file and use that. Python has a way to do that with os.path.dirname.

import os.path
print(os.path.dirname(__file__))

In this case it would lead to the following code:

import os.path
filepath = os.path.dirname(__file__)
carImg = pygame.image.load(os.path.join(filepath, "racecar.png"))

Here is an alternative implementation using the wonderful pathlib:

import pathlib
filepath = pathlib.Path(__file__).parent
carImg = pygame.image.load(filepath / "racecar.png")

Leave a Comment