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

Question:

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:Usersjulix>C:UsersjulixDocumentstestpygame_tutorial.py
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:UsersjulixDocumentstestpygame_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

Asked By: frikai

||

Answers:

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")
Answered By: Matthias

I would suggest an easy solution, I got stuck at the same stage.
I was coding in VS Code and later realized that the terminal is currently executing code from parent directory.
So to import image I just need to get the terminal into my current working directory and then run the program again.
Images were load fine without any error.

Just make sure in the terminal you are executing code from the same working directory as the project folder.

Answered By: Nishant Saxena

I’ve same problem. but for me, it’s wrong about file name.

*sub_img = os.path.join(img_folder, 'submarine.png.png')
        self.image = pygame.image.load(sub_img).convert()*

I was edit my file name " submarine.png " after downloaded.
So, This file is name submarine.png type png.
You can fix it by change file name to just "submarine"

I hope it’s helpful.

Answered By: Goodbye
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.