How can you access files after being compiled to a single python executable?
Question:
I have a python script that reads a local file (let’s call it file.foo
). When I compile the script, I need that local file inside the executable so i use pyinstaller like this:
> pyinstaller --onefile --add-data "file.foo" "script.py"
The thing is, when I run the executable, my script cannot find file.foo
which is embedded with it.
Is there a way to read files compiled within the executable?
PS: I would prefer using --onefile
to keep it closed source
Answers:
pyinstaller will unpack your file into a temporary folder at runtime inside the operating system TEMP folder, so in order to get the path of the file after it is unpacked using the code in this answer
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
then to get the path of the data, just use
data_path = resource_path("file.foo")
with open(data_path,'r') as f:
pass # read it as you normally would
just a note, --onefile
can cause some libraries not to work, so make sure you test your dependences first.
I have a python script that reads a local file (let’s call it file.foo
). When I compile the script, I need that local file inside the executable so i use pyinstaller like this:
> pyinstaller --onefile --add-data "file.foo" "script.py"
The thing is, when I run the executable, my script cannot find file.foo
which is embedded with it.
Is there a way to read files compiled within the executable?
PS: I would prefer using --onefile
to keep it closed source
pyinstaller will unpack your file into a temporary folder at runtime inside the operating system TEMP folder, so in order to get the path of the file after it is unpacked using the code in this answer
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
then to get the path of the data, just use
data_path = resource_path("file.foo")
with open(data_path,'r') as f:
pass # read it as you normally would
just a note, --onefile
can cause some libraries not to work, so make sure you test your dependences first.