0

for this really simple program, it took the images from the file that the script was in. this was a few days ago. now it takes the files from my c_drive.

I fixed this by using the os module and changing the string, but this looks really inefficient.

import os
import pygame

file = os.path.realpath(__file__)
print(file)
path = file.replace('code.py', '')
os.chdir(path)

pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('code')
icon = pygame.image.load('idle1.png').convert()
pygame.display.set_icon(icon)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    pygame.display.update()

is there a more effecient way to do this? is my python broken?

  • How about using `os.path.dirname()` or explicitly setting the full path name through configuration? – Roeften Mar 16 '22 at 22:36
  • If accessing a file via a relative path is looking in a different place than you expect then there are plenty of possible reasons, very few of them directly related to Python or your code. Are you running the script in an IDE? Via a shortcut? Are you specifying the script via an absolute path while your terminal's current directory is the root of the drive? – Kemp Mar 16 '22 at 22:43
  • @Roeften i dont want to explicitly set the full path because i plan on sharing the file with friends. if i use the full pathname, i dont think it would work on any other computer. I did try to use ```os.path.dirname()``` but this has not reduced the number of lines of code. thank you for the response though! – wasteOfOxygen Mar 17 '22 at 05:54
  • @Kemp i am running a script in vscode. I would like to make future programs into executables so 'cd'ing into a directory and running the script would not be ideal. I do not want to use an absolute path because i think that will mean that the program will only work on this computer, and will not work if put in a different directory. – wasteOfOxygen Mar 17 '22 at 05:58
  • One option instead of changing the working directory within your code (which I assume is what you're trying to avoid) is to simply use the full path when opening the file. See [this answer](https://stackoverflow.com/a/47388482/3228591) for a snippet that will work to find the path the script is in when run as a script and also the path the exe is in if you make a single-file executable (which must be handled differently). Then you can do `pygame.image.load(os.path.join(app_path, 'idle1.png'))` when loading. – Kemp Mar 17 '22 at 08:43

0 Answers0