[Python] Use importlib.resources for files inside the top level parent module

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I want to load a file from my python module using importlib.resources (see also this question). If the file is inside a submodule, this is straight forward (run using python -m, see here):

    import importlib.resources
    from . import submodule

    print(importlib.resources.files(submodule).joinpath("file.txt").read_bytes())


    For files in the same module, it is possible to use __package__:

    import importlib.resources

    print(importlib.resources.files(__package__).joinpath("file.txt").read_bytes())


    However, I cannot get this approach to work for files inside the top level module, if I want to access them from a submodule:

    module
    ├── file.txt
    ├── __init__.py
    └── submodule
    ├── __init__.py
    └── submodule_script.py


    import importlib.resources

    from ... import module # ImportError: attempted relative import beyond top-level package
    import .. as module # SyntaxError: invalid syntax
    from .. import . as module # SyntaxError: invalid syntax

    print(importlib.resources.files(module).joinpath("file.txt").read_bytes())


    How can I obtain an import-like reference to the top level module location, such that importlib.resources can understand it?

    Continue reading...

Compartilhe esta Página