Home > Mobile >  Python searching for image in wrong directory
Python searching for image in wrong directory

Time:04-10

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()

CodePudding user response:

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()

CodePudding user response:

You don't need to change the default directory. Just load from the full directory. That should look something like: "C:\Users\...\Python\Snake\Graphics\apple.png".

CodePudding user response:

I think the simplest way is to first see your active directory by simply typing in pwd, and then you could simply change the directory by cd("C:/path/to/location"), remember you have to use the backslash, or just use the following library:

import os
os.chdir("C:/path/to/location")

As pydragon posted, you could also import it by just giving the import function a path.

  • Related