pythonfilefilenotfounderror

Python searching for image in wrong directory


I am trying to load some assets onto my program that I have them in a folder called 'Graphics', which is inside the folder 'Snake', which is inside the folder 'Projects', which is inside the folder 'Python'. However, also inside that folder 'Python' is another folder named 'HelloWorld'.

I am trying to load some assets in a program that I am running in 'Snake' and Python is searching for the assets in the 'HelloWorld' folder (which is where I used to keep my python files).

I get the error:

FileNotFoundError: No file 'Projects/Snake/Graphics/apple.png' found in working directory 'C:\Users\35192\OneDrive - WC\Desktop\Python\HelloWorld'

I believe that for this I have to change the default directory for vs code. I have changed the default directory for the command prompt and it did nothing. Perhaps this is because the python that I am running in the command prompt is different from the one in vs code (?)

How do I fix this?

Thank you in advance.

Edit: This is how I am currently loading the image: apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()


Solution

  • Use pathlib to construct the path to your images. You wil have to add import pathlib to your code.

    pathlib.Path(__file__) will give you the path to the current file. pathlib.Path(__file__).parent will give you the folder. Now you can construct the path with the / operator.

    Try the following code and check the output.

    import pathlib
    
    print(pathlib.Path(__file__))
    print(pathlib.Path(__file__).parent)
    print(pathlib.Path(__file__).parent / 'Grahics' / 'apple.png')
    

    Now you will be able to move the full project to a totally different folder without having to adjust any code.


    Your code example looks like this: apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()

    If you import pathlib you can replace that with the dynamic approach:

    path_to_image= pathlib.Path(__file__).parent / 'Grahics' / 'apple.png'
    apple = pygame.image.load(path_to_image).convert_alpha()
    

    I'm quite sure that pygame can work with a path from pathlib. If not then you have to convert the path to a string manually

    apple = pygame.image.load(str(path_to_image)).convert_alpha()