{"record":{"id":"f39bc862f9da397e","repo":"sqlalchemy/alembic","slug":"can-t-find-python-file-s","errorCode":null,"errorMessage":"Can't find Python file %s","messagePattern":"Can't find Python file (.+?)","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"alembic/util/pyfiles.py","lineNumber":118,"sourceCode":"def load_python_file(\n    dir_: str | os.PathLike[str], filename: str | os.PathLike[str]\n) -> ModuleType:\n    \"\"\"Load a file from the given path as a Python module.\"\"\"\n\n    dir_ = pathlib.Path(dir_)\n    filename_as_path = pathlib.Path(filename)\n    filename = filename_as_path.name\n\n    module_id = re.sub(r\"\\W\", \"_\", filename)\n    path = dir_ / filename\n    ext = path.suffix\n    if ext == \".py\":\n        if path.exists():\n            module = load_module_py(module_id, path)\n        else:\n            pyc_path = pyc_file_from_path(path)\n            if pyc_path is None:\n                raise ImportError(\"Can't find Python file %s\" % path)\n            else:\n                module = load_module_py(module_id, pyc_path)\n    elif ext in (\".pyc\", \".pyo\"):\n        module = load_module_py(module_id, path)\n    else:\n        assert False\n    return module\n\n\ndef load_module_py(module_id: str, path: str | os.PathLike[str]) -> ModuleType:\n    spec = importlib.util.spec_from_file_location(module_id, path)\n    assert spec\n    module = importlib.util.module_from_spec(spec)\n    spec.loader.exec_module(module)  # type: ignore\n    return module\n\n\ndef _preserving_path_as_str(path: str | os.PathLike[str]) -> str:","sourceCodeStart":100,"sourceCodeEnd":136,"githubUrl":"https://github.com/sqlalchemy/alembic/blob/5551b5d35f985c99cb8f1af2b3c526b050e4c059/alembic/util/pyfiles.py#L100-L136","documentation":"Raised as ImportError by load_python_file when the requested .py file does not exist on disk and no compiled .pyc/.pyo fallback can be found (pyfiles.py:112-118). load_python_file is used to dynamically load env.py, custom env.py modules, and migration scripts. The function first checks for the .py file, then tries pyc_file_from_path for a bytecode fallback; if both fail, the ImportError is raised.","triggerScenarios":"Calling load_python_file(dir_, filename) where dir_/filename doesn't exist and no .pyc sibling exists. Happens when Alembic's config points to a nonexistent env.py or when the script_location directory is wrong. Also triggered by 'alembic edit' or migration execution when the script file was deleted.","commonSituations":"Incorrect script_location in alembic.ini pointing to a non-existent migrations directory. env.py was accidentally deleted or never created (e.g., interrupted 'alembic init'). Running from the wrong working directory so relative paths don't resolve. Filesystem case sensitivity issues on Linux (Env.py vs env.py).","solutions":["Verify the script_location path in alembic.ini/pyproject.toml points to the correct existing directory.","Check that env.py exists: ls <script_location>/env.py.","If the migrations directory was never created, run alembic init <directory> to scaffold it.","Ensure you're running alembic from the correct working directory, or use absolute paths in the config.","Check file permissions and case sensitivity (env.py, not Env.py or ENV.PY)."],"exampleFix":"# before: alembic.ini\n[alembic]\nscript_location = ./migrations  # directory doesn't exist\n\n# after\n[alembic]\nscript_location = ./alembic   # correct directory with env.py\n\n# or scaffold the directory\nalembic init alembic","handlingStrategy":"validation","validationCode":"import os\n\ndef python_file_exists(directory, filename):\n    path = os.path.join(directory, filename)\n    if os.path.exists(path):\n        return True\n    # check for .pyc fallback\n    base, _ = os.path.splitext(path)\n    import importlib.machinery\n    for ext in importlib.machinery.BYTECODE_SUFFIXES:\n        if os.path.exists(base + ext):\n            return True\n    return False","typeGuard":null,"tryCatchPattern":"try:\n    module = load_python_file(dir_, filename)\nexcept ImportError as e:\n    if \"Can't find Python file\" in str(e):\n        print(f\"File not found: {os.path.join(dir_, filename)}\")\n        print(\"Check script_location in your config and ensure env.py exists.\")\n    raise","preventionTips":["Verify script_location in alembic.ini points to a real directory containing env.py.","Run alembic from the project root so relative paths resolve correctly.","Use absolute paths in config to avoid working-directory issues.","Ensure 'alembic init' completed successfully before running other commands."],"tags":["alembic","file-not-found","config","env-py","importerror"],"backgroundTag":null,"analyzedSha":"5551b5d35f985c99cb8f1af2b3c526b050e4c059","analyzedAt":"2026-08-11T01:38:46.612Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}