Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can you access files after being compiled to a single python executable?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS: I would prefer using --onefile to keep it closed source

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading