Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyinstaller add-data file not found

I'm trying to make an executable from a very simple python file which reads a json file.

In my folder there are only this two files:

test.py
data.json

So I run:

pyinstaller -F --add-data "data.json;data.json" test.py

This creates a dist folder where I can find my test.exe. However when I run the exe file it cannot find data.json

FileNotFoundError: [Errno 2] No such file or directory: 'data.json'
[18556] Failed to execute script test

My file is super simple:

import json

# data.json is in the same folder as test.py, so no path is provided
with open("data.json") as f:
    data = json.load(f)
    print(data)

Edit:

Ok, it looks that when I compile the exe, I have to execute it from the same folder I compiled it, so I have to do:

./dist/test.exe

If I change folder to dist and then I execute the file from there it doesnt work

cd dist
test.exe   --> Fails

This is clearly not what I want. I should eb able to call the exe from whatever folder I want. data.json was included from the same folder where test.py was, so inside the exe they should also be in the same "folder"


1 Answers

Add this to the top of your run script.

import sys, os

os.chdir(sys._MEIPASS)

This should fix the issue. The reason this works is because when you use one file mode; everytime the app is run, a new directory is created in your computers temp folder. All dependencies are then unpacked into this folder. Pyinstaller stores this directory in sys._MEIPASS. So you need to change the cwd to access the files if you want to use a relative path.

like image 184
Robert Kearns Avatar answered Oct 28 '25 20:10

Robert Kearns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!