Reputation: 13
Im trying to program chess in python using pygame but i cant load images from a diferent directory, here's the code.
king=pygame.image.load(os.path.basename(r"C:\Users\tiago\PycharmProjects\chess\pieces\w_king.png"))
pos = [4, 0]
coords = translate_coord(pos)
display.blit(king, coords)
pygame.display.flip()
i keep getting the "FileNotFoundError: No such file or directory." error and i don know whats wrong.
Upvotes: 1
Views: 867
Reputation: 51
Don't use os.path.basename
This returns w_king.png
in your case.
It looks like pygame.image.load
requires a file type object. You can obtain this using open()
with open(r"C:\Users\tiago\PycharmProjects\chess\pieces\w_king.png") as filehandle:
king=pygame.image.load(filehandle)
# do stuff with king
pos = [4, 0]
coords = translate_coord(pos)
display.blit(king, coords)
pygame.display.flip()
Edit: Never mind, looks like pygame.image.load
can also handle a file path string although I believe my answer also works.
Upvotes: 0
Reputation: 293
You can just pass the file path string to pygame.image.load
without using os.path.basename
. Also, you can pass a relative path instead, and if you want to make the file path cross platform, you can call os.path.join()
like this, assuming the current working directory is C:\Users\tiago\PycharmProjects\chess
:
king = pygame.image.load(os.path.join("pieces", "w_king.png"))
The issue with what you have is that os.path.basename
is returning w_king.png
, but assuming your current working directory is C:\Users\tiago\PycharmProjects\chess
, pygame cannot find the file because what it actually needs to find is pieces\w_king.png
, hence why in my solution above I have os.path.join("pieces", "w_king.png"))
, which would return pieces\w_king.png
on your system.
Edit:
As mentioned by @Rabbid76 you should make sure that the current working directory is the same directory as the source file before the code to load the image, if you are passing a relative path, like so:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
king = pygame.image.load(os.path.join("pieces", "w_king.png"))
Upvotes: 1