Pyinstaller include json file

Pyinstaller Include JSON File

PyInstaller is a tool used to package Python scripts into standalone executables. You can include JSON files in the packaged executable by following these steps:

  1. Create a directory called “json_files” in your project directory, and place your JSON files inside this folder. For example, let’s assume you have a file named “data.json”.
  2. In your Python script, you can access the JSON file using the relative path. For example, if your script is in the same directory as the “json_files” folder, you can access the “data.json” file using the path “./json_files/data.json”.
  3. Open your terminal or command prompt and navigate to your project directory.
  4. Run the PyInstaller command to package your script. For example:
    pyinstaller --add-data "json_files;json_files" your_script.py
    This command includes the “json_files” folder and its contents in the executable.
  5. After the packaging process is complete, you will find a “dist” folder in your project directory. Inside this folder, you will find the standalone executable file for your script.

Here’s an example to illustrate the usage of PyInstaller with a JSON file:

        
import json

def read_json_file(file_path):
    with open(file_path, 'r') as file:
        data = json.load(file)
    return data

data = read_json_file('./json_files/data.json')
print(data)
        
    

Make sure to adjust the file paths and names according to your project structure. The above example assumes that the “data.json” file is inside the “json_files” folder, located in the same directory as your script.

Leave a comment