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()
-
Could you show us some of the code that's giving you a problem?GWW– GWW2011年01月17日 02:28:37 +00:00Commented 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.Apalala– Apalala2011年01月17日 14:50:40 +00:00Commented Jan 17, 2011 at 14:50
2 Answers 2
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.
Comments
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.