The --add-data
option allows you to include additional non-code files (such as data files, configuration files) in your packaged application.
When the program runs, PyInstaller's bootloader will extract these files to a temporary directory, with the path stored in sys._MEIPASS
;
Adding and Accessing Resources
Save the following content to mydata.txt
to be used as program data, which will be bundled with the application:
hello world
Write code to obtain the full path of mydata.txt
and read its contents:
import sys
import os
def get_source_path(relative_path):
if hasattr(sys,'_MEIPASS'):
# Program is running in packaged mode
base_path = sys._MEIPASS
else:
# Program is running in development mode
base_path = os.path.abspath(".")
return os.path.join(base_path,relative_path)
# Get the correct file path
data_file_path = get_source_path('mydata.txt')
with open(data_file_path, 'r') as f:
print(f.read())
Save the code as myscript.py
;
Package it using the --add-data
option:
pyinstaller -F myscript.py --add-data mydata.txt:.
You can also change the resource location:
pyinstaller -F myscript.py --add-data mydata.txt:data2
The reading path would then become:
data_file_path = get_source_path('data2/mydata.txt')