当前位置: 动力学知识库 > 问答 > 编程问答 >

running python from another directory

问题描述:

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

网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: