Pyinstaller Unable to access Data Folder

When pyInstaller (or cx_Freeze, py2exe, etc.) make an executable, all the program files, along with PyGame, Python and a bunch of other stuff is all compressed up.

When it’s run, the first thing to happen is that archive of stuff is unpacked. Unpacked somewhere. Then your executable is started, but not from the location of the unpack.

To fix this, your script has to determine the location it is running from – that is the full path to the script. Then use this location to find all the program’s extra files.

import sys
import os.path

if getattr(sys, 'frozen', False):
    EXE_LOCATION = os.path.dirname( sys.executable ) # cx_Freeze frozen
else:
    EXE_LOCATION = os.path.dirname( os.path.realpath( __file__ ) ) # Other packers

Then when loading a file, determine the full path with os.path.join:

my_image_filename = os.path.join( EXE_LOCATION, "images", "xenomorph.png" )
image = pygame.image.load( my_image_filename ).convert_alpha()

my_sound_filename = os.path.join( EXE_LOCATION, "sounds", "meep-meep.ogg" )
meep_sound = pygame.mixer.Sound( my_sound_filename )

It may be possible to use os.chdir( EXE_LOCATION ) to set the directory once, and thus make less changes, but I think being careful about paths is the best approach.

Leave a Comment