1

Hallo,

if i try to run a python script from another directory, it tells me everytime that he cannot find all the ressource files:

pygame.error: Couldn't open ../data/icon.png

etc..

I think this is because of the relative paths and the now changed working directory?

Am I right? and how can i avoid this?

greetings

Edit: Loading code:

path = os.path.join('..', 'data', 'gfx',  filename)
blah = pygame.image.load(path).convert_alpha()
2
  • Could you show us some of the code that's giving you a problem? Commented Jan 17, 2011 at 2:28
  • The .. in the example may indicate that the data directory is not within the program modules. As other have mentioned, it is best to use the module paths to recover non .py files. Commented Jan 17, 2011 at 14:50

2 Answers 2

4

You are correct. This can be avoided in the script by using __file__ to get the location of the current module and the various functions in os.path to generate absolute paths based on the value.

Sign up to request clarification or add additional context in comments.

Comments

1

Assume that your project is a directory in your file system and if you are referencing the modules and scripts within your project, using relative paths is fine and when you are distributing, you have to distribute the whole directory. But if you are referencing some external path, outside of your project folder, make sure that you code the absolute path, so that you won't face the problem that you are currently facing. You could get the path, by os.getcwd() if you put it anywhere the in the module. This would give the path as were your python is executing from and you will have to see that files you have referenced are accessible from that path.

2 Comments

os.getcwd() doesn't give you any information about the module. That is what __file__ is for.
Ignacio, its not for the module, it is for where the python process is being executed from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.