I try to access to one of my pictures in one of my directories but i get an error each time. Actually, my folder is like that :
gamefolder:
lib:
main.py
level.py
othermodules.py
...
data:
Level1.png
otherspictures.png
In the primary python file who is main.py, i wrote :
currentpath = os.path.dirname(sys.argv[0])
parentpath = os.path.dirname(currentpath)
sys.path.append(os.path.join(parentpath, 'data'))
But I always get an error in one of my script : level.py called by main.py :
pygame.error: Couldn't open Level_1.png
The code in level.py is like that :
self.image = pygame.image.load('Level1.png').convert_alpha()
I'm not yet familiar with python path .. But it would be so nice if i can arrange that folder like that, which is very elegant !
Thanks to help :)
Try
currentpath = os.path.dirname(os.path.realpath(__file__))
# or
#currentpath = os.path.dirname(os.path.realpath(sys.argv[0]))
datadir = os.path.join(os.path.dirname(currentpath), 'data')
self.image = pygame.image.load(os.path.join(datadir, 'Level1.png')).convert_alpha()
The path sys.argv[0]
can be main.py and its dirname
is an empty string
Updated
As the manual of pygame
You should use os.path.join()
for compatibility.