Convert Python to EXE with PyInstaller: One-File Apps, Data Files and Hidden Imports (2026)

Modern Python Tools And Libraries Nov 16, 2026

Watch on YouTube

You wrote a useful Python script, and now a colleague wants to run it. They do not have Python, they do not know what a virtual environment is, and they just want to double-click a file. PyInstaller solves exactly this: it bundles your script, the Python interpreter and every library it imports into one folder or one executable file that runs on a machine with no Python installed. In this guide we turn a small reporting tool into a single executable, bundle a data file correctly with sys._MEIPASS, hit and fix the most common error (a missing hidden import), compare one-file and one-folder builds with real sizes and start-up times, and cover the Windows options for icons and console windows. Everything was tested with PyInstaller 6.22.3 (contrib hooks 2026.10) on Python 3.14.10, and every output block below is the real output of the command above it.

What PyInstaller actually does

PyInstaller is not a compiler. It analyses your imports, collects the .pyc bytecode of your code and its dependencies, copies the Python shared library and any binary extensions, and adds a small native bootloader that starts the bundled interpreter. That has three practical consequences:

  • Build on the target operating system. A build made on Windows gives a Windows .exe; a build made on Linux gives a Linux binary; macOS gives a macOS app. There is no cross-compiling, so use one CI runner per OS if you ship to several.
  • Your source is not secret. Bytecode can be decompiled. Do not put passwords or API keys in a frozen app.
  • The file is large because it contains a whole Python runtime. Ten to forty megabytes for a small tool is normal.

Version notes for 2026: PyInstaller added Python 3.14 support in 6.15 and Python 3.15 support in 6.21 (June 2026). The source:dest form of --add-data with a colon works on every platform, including Windows, so one build command can serve all three systems.

Install

python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install pyinstaller        # 6.22.3 at the time of writing
pyinstaller --version

Install PyInstaller in the same virtual environment as your app's dependencies. It bundles whatever it finds in the active environment, so a clean, minimal venv gives a smaller and more predictable executable. If you manage environments with uv, as shown in uv + Ruff: The Fastest Python Workflow, uv add --dev pyinstaller followed by uv run pyinstaller ... works the same way.

Step 1: The app we will package

Our example is sales-report, a tiny command-line tool. It reads prices and sales from config.json, picks an exporter module by name at run time (exporter_csv or exporter_json), and writes a report file. It contains the two patterns that break most first builds: a data file read from disk and a module imported from a string. The two helper functions are the important part:

"""sales-report: a small CLI we turn into a single executable with PyInstaller."""
import argparse, importlib, json, platform, sys
from pathlib import Path

def resource_path(name: str) -> Path:
    """Find files bundled with --add-data, both in dev and in the frozen app."""
    base = getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)
    return Path(base) / name

def app_dir() -> Path:
    """Folder for user output: next to the .exe when frozen, next to the script otherwise."""
    if getattr(sys, "frozen", False):
        return Path(sys.executable).resolve().parent
    return Path(__file__).resolve().parent

def main() -> None:
    parser = argparse.ArgumentParser(prog="sales-report")
    parser.add_argument("--format", choices=["csv", "json"], default="csv")
    args = parser.parse_args()

    config = json.loads(resource_path("config.json").read_text())
    exporter = importlib.import_module(f"exporter_{args.format}")   # loaded by name at run time

    rows = [(r["region"], r["units"] * config["unit_price"]) for r in config["sales"]]
    out = app_dir() / f"report.{args.format}"
    exporter.write(rows, out, currency=config["currency"])

    print(f"frozen={getattr(sys, 'frozen', False)}  python={platform.python_version()}")
    print(f"config from: {resource_path('config.json').parent.name}")
    print(f"total = {sum(v for _, v in rows):,.2f} {config['currency']}")
    print(f"saved {out.name} ({out.stat().st_size} bytes) in {out.parent}")

if __name__ == "__main__":
    main()

resource_path() finds bundled read-only files. A one-file executable unpacks itself into a temporary folder at start-up and stores that path in sys._MEIPASS; when you run the plain script, the attribute does not exist and the function falls back to the script's folder. app_dir() is for files the user should see, such as the report: next to the executable when frozen (sys.frozen is True), otherwise next to the script. Never write output into sys._MEIPASS; it is deleted when a one-file app exits. The data file and the two small exporters look like this:

{
  "currency": "USD",
  "unit_price": 19.5,
  "sales": [
    {"region": "North", "units": 120},
    {"region": "South", "units": 85},
    {"region": "East", "units": 143},
    {"region": "West", "units": 97}
  ]
}
import csv

def write(rows, path, currency):
    with open(path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["region", f"revenue_{currency.lower()}"])
        w.writerows((region, f"{value:.2f}") for region, value in rows)
import json

def write(rows, path, currency):
    data = [{"region": r, "revenue": round(v, 2), "currency": currency} for r, v in rows]
    path.write_text(json.dumps(data, indent=2))

First, check that it works as a normal script:

$ python report.py
frozen=False  python=3.14.10
config from: sales-report
total = 8,677.50 USD
saved report.csv (78 bytes) in /tmp/sales-report

Step 2: The first build, and the classic error

--onefile asks for a single executable, --name sets its file name, and --add-data "config.json:." copies the JSON file into the root of the bundle (source, colon, destination folder inside the app):

$ pyinstaller --onefile --name sales-report --add-data "config.json:." report.py
INFO: PyInstaller: 6.22.3, contrib hooks: 2026.10
INFO: Python: 3.14.10
INFO: Platform: Linux-6.12.113+-x86_64-with-glibc2.41
INFO: Building EXE from EXE-00.toc
INFO: Building EXE from EXE-00.toc completed successfully.
INFO: Build complete! The results are available in: /tmp/sales-report/dist
$ ./dist/sales-report
  File "<frozen importlib._bootstrap>", line 1371, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1335, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'exporter_csv'
[PYI-897530:ERROR] Failed to execute script 'report' due to unhandled exception!
exit code: 1

The build succeeded, but the program crashed. PyInstaller finds modules by reading import statements. importlib.import_module(f"exporter_{args.format}") builds the module name from a string at run time, so the analyser never saw exporter_csv and did not bundle it. The same happens with plugin systems, some database drivers and libraries that load backends by name. The traceback, ModuleNotFoundError in the frozen app while the script works fine, is the signature of a hidden import.

Step 3: Fix hidden imports and run without Python

List every dynamically loaded module with --hidden-import. --clean clears PyInstaller's cache and -y overwrites the previous build without asking. To prove the result is self-contained, we copy the executable to a new folder and start it with env -i, which removes every environment variable, including PATH and the virtual environment:

$ pyinstaller --onefile --name sales-report --add-data "config.json:." \
    --hidden-import exporter_csv --hidden-import exporter_json --clean -y report.py
INFO: PyInstaller: 6.22.3, contrib hooks: 2026.10
INFO: Python: 3.14.10
INFO: Platform: Linux-6.12.113+-x86_64-with-glibc2.41
INFO: Building EXE from EXE-00.toc
INFO: Building EXE from EXE-00.toc completed successfully.
INFO: Build complete! The results are available in: /tmp/sales-report/dist
$ ls -lh dist/
-rwxr-xr-x 13M sales-report
$ cd /tmp/delivery && env -i ./sales-report --format json   # no venv, no PATH, no Python
frozen=True  python=3.14.10
config from: _MEI000db272LBpKiP
total = 8,677.50 USD
saved report.json (308 bytes) in /tmp/delivery
exit code: 0
$ head -6 /tmp/delivery/report.json
[
  {
    "region": "North",
    "revenue": 2340.0,
    "currency": "USD"
  },

This time the executable ran with no Python on the path: frozen=True, the interpreter version is the one bundled inside the file, config.json was read from the temporary _MEI... folder, and the report was saved next to the executable in /tmp/delivery, exactly where a user would look for it. The 13 MB file is everything the user needs.

Step 4: Repeatable builds, one-file vs one-folder

Typing long commands does not scale. PyInstaller can be driven from Python with PyInstaller.__main__.run(), which takes the same arguments as the command line. The script below builds both modes, measures their size and the median start-up time over five runs, and uses os.pathsep so it runs unchanged on Windows:

"""Repeatable build: onefile vs onedir, then smoke-test both executables."""
import os, shutil, statistics, subprocess, time
from pathlib import Path
import PyInstaller.__main__

COMMON = ["report.py", "--name", "sales-report", "--add-data", f"config.json{os.pathsep}.",
          "--hidden-import", "exporter_csv", "--hidden-import", "exporter_json",
          "--noconfirm", "--clean", "--log-level", "WARN"]

def build(mode: str) -> Path:
    PyInstaller.__main__.run(COMMON + [f"--{mode}", "--distpath", f"dist-{mode}"])
    name = "sales-report.exe" if os.name == "nt" else "sales-report"
    return Path(f"dist-{mode}") / ("" if mode == "onefile" else "sales-report") / name

def size_mb(path: Path) -> float:
    files = [path] if path.is_file() else [p for p in path.rglob("*") if p.is_file()]
    return sum(p.stat().st_size for p in files) / 1_048_576

def startup_ms(exe: Path, runs: int = 5) -> float:
    times = []
    for _ in range(runs):
        t = time.perf_counter()
        subprocess.run([str(exe.resolve())], check=True, capture_output=True, env={})
        times.append((time.perf_counter() - t) * 1000)
    return statistics.median(times)

for mode in ("onefile", "onedir"):
    exe = build(mode)
    shipped = exe if mode == "onefile" else exe.parent
    files = 1 if mode == "onefile" else sum(1 for p in shipped.rglob("*") if p.is_file())
    print(f"{mode:8} {str(exe):40} {size_mb(shipped):5.1f} MB  {files:3} files  "
          f"median start {startup_ms(exe):4.0f} ms")
shutil.rmtree("build", ignore_errors=True)
print("spec file kept for next builds:", Path("sales-report.spec").exists())
$ python build_exe.py
onefile  dist-onefile/sales-report                 12.8 MB    1 files  median start  204 ms
onedir   dist-onedir/sales-report/sales-report     35.3 MB    4 files  median start   55 ms
spec file kept for next builds: True

The trade-off is clear. One-file is a single compressed 12.8 MB file that is easy to e-mail or download, but every launch first unpacks the runtime into a temporary folder, so it started in about 204 ms. One-folder (the default) is larger on disk because nothing is compressed, but it starts in about 55 ms and updates are easier because you can replace single files. Since PyInstaller 6, everything except the executable sits in an _internal subfolder, so the folder stays tidy. Our interpreter build links most of the standard library statically, so the folder holds only four files; a typical Windows installation will produce more DLL and .pyd files. Use one-file for small tools you hand to people and one-folder for larger apps you install. Every build also writes sales-report.spec, a Python file with the full configuration; commit it and later run pyinstaller sales-report.spec to rebuild with identical settings.

Windows options: icon, no console window, version

pyinstaller --onefile --windowed --name SalesReport ^
    --icon app.ico --add-data "config.json:." ^
    --hidden-import exporter_csv --hidden-import exporter_json report.py

--windowed (alias --noconsole) hides the black console window, which you want for Tkinter, PySide6 or other GUI apps but not for command-line tools, because print() output would disappear. --icon takes an .ico file on Windows or .icns on macOS; with Pillow installed, PyInstaller can also convert a PNG. The executable lands in dist\SalesReport.exe. If you build a CLI like the ones in Typer + Rich: Build Beautiful Modern CLIs in Python, keep the console and use one-folder mode for the fastest start.

Quick reference

TaskOption or code
Single executable--onefile
Folder build (default)--onedir
Name the output--name sales-report
Bundle a file or folder--add-data "config.json:.", --add-data "templates:templates"
Module loaded by name--hidden-import exporter_csv
Whole package with data--collect-all package_name
No console window--windowed
Icon--icon app.ico
Fresh rebuild--clean -y
Bundled file pathPath(getattr(sys, "_MEIPASS", script_dir)) / name
Running frozen?getattr(sys, "frozen", False)
Rebuild from configpyinstaller sales-report.spec

Common problems and fixes

  • ModuleNotFoundError only in the executable: a hidden import. Add --hidden-import name, or --collect-submodules package for plugin packages. Run the executable from a terminal to see the traceback.
  • FileNotFoundError for a JSON, image or model file: the file was not bundled, or the code uses a path relative to the current folder. Add it with --add-data and open it through resource_path().
  • Python shared library ('libpython3.13.so.1.0') was not found: we hit this on Debian with the system Python, which ships without the shared library. Install the libpython3.13 package, or use a Python from python.org, pyenv or uv, which include it.
  • Antivirus flags the new .exe: unsigned one-file executables are a common false positive. Prefer one-folder builds, keep PyInstaller up to date, sign the executable with a code-signing certificate, and report false positives to the vendor.
  • The app saves files in a strange temp folder: you wrote output relative to __file__ or sys._MEIPASS. Use Path(sys.executable).parent or the user's documents folder instead.
  • Huge executable: build from a clean venv with only the packages you need. Heavy libraries such as PyTorch, SciPy or pandas bring hundreds of megabytes; if your Excel reports from openpyxl: Automate Excel Files with Python also use pandas, prefer one-folder mode.
  • "Exec format error" or the file will not open on another computer: you built on a different operating system or CPU architecture. Rebuild on the target system; on Linux, build on the oldest glibc you want to support.

Conclusion

Converting Python to an executable comes down to a short checklist: install PyInstaller in a clean venv, read bundled files through sys._MEIPASS and write output next to sys.executable, declare anything imported by name with --hidden-import, choose one-file for easy sharing or one-folder for speed, and keep the .spec file so every build is identical. Test the result on a machine, or at least in an empty environment, without Python, exactly as we did with env -i, and your script is ready for people who will never open a terminal.

Share:
Last updated: November 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices