[python] Bundling data files with PyInstaller (--onefile)

Another solution is to make a runtime hook, which will copy(or move) your data (files/folders) to the directory at which the executable is stored. The hook is a simple python file that can almost do anything, just before the execution of your app. In order to set it, you should use the --runtime-hook=my_hook.py option of pyinstaller. So, in case your data is an images folder, you should run the command:

pyinstaller.py --onefile -F --add-data=images;images --runtime-hook=cp_images_hook.py main.py

The cp_images_hook.py could be something like this:

import sys
import os
import shutil

path = getattr(sys, '_MEIPASS', os.getcwd())

full_path = path+"\\images"
try:
    shutil.move(full_path, ".\\images")
except:
    print("Cannot create 'images' folder. Already exists.")

Before every execution the images folder is moved to the current directory (from the _MEIPASS folder), so the executable will always have access to it. In that way there is no need to modify your project's code.

Second Solution

You can take advantage of the runtime-hook mechanism and change the current directory, which is not a good practice according to some developers, but it works fine.

The hook code can be found below:

import sys
import os

path = getattr(sys, '_MEIPASS', os.getcwd())   
os.chdir(path)