Search code examples
pythonpygamecommand-prompt

pygame.error "couldn't open image.png" only in command prompt


I've got a very simple python program I wrote to learn pygame, and among other things I use an image.

When I run the program with PyCharm, or when I run it by double-clicking on the file, it works fine. However, if I try to run it through the command prompt, I get the following error:

C:\Users\julix>C:\Users\julix\Documents\test\pygame_tutorial.py
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\julix\Documents\test\pygame_tutorial.py", line 21, in <module>
    carImg = pygame.image.load("racecar.png")
pygame.error: Couldn't open racecar.png

This is the line in my code it refers to:

carImg = pygame.image.load("racecar.png")

The image "racecar.png" is located in exactly the same directory as the program. The confusing part is that my code seems to be fine since there are no errors when I run it by double-clicking.

Can post full code if necessary. Thanks in advance


Solution

  • 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")