2

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"

Sembei Norimaki
  • 5,656
  • 2
  • 31
  • 62
  • Are you running the script from the same directory where your data.json file is present? – Laura Smith Aug 13 '19 at 15:27
  • I'm running pyinstaller it from the folder where test.py and data.json is. Then to run the exe I first go to the dist subfolder – Sembei Norimaki Aug 13 '19 at 15:29
  • Is the json in the same folder where the exe is present? – Laura Smith Aug 13 '19 at 15:33
  • No, the json is inside the exe. I have a python file and a json file in the same folder. The python file expects the json to be in the same folder, but when I make an exe I want json to be accessible – Sembei Norimaki Aug 13 '19 at 15:36
  • 2
    Seeing this issue is becoming dated, please post your solution if you found it. Researching this myself now... – bblue Jan 09 '20 at 16:26
  • Hey @SembeiNorimaki I have the same problem now. Have you found a proper solution? My csv-file is in the same folder as my .py script but I get the same error that the file can't be found. A lot of solutions [like this](https://stackoverflow.com/questions/14296833/pyinstaller-onefile-doesnt-find-data-files) are using `sys._MEIPASS` which doesn't get me further. It throws the error `AttributeError: module 'sys' has no attribute '_MEIPASS'`. – QuagTeX Mar 17 '22 at 17:24

1 Answers1

4

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.

Robert Kearns
  • 1,591
  • 1
  • 6
  • 15