Python "importlib.resources" FileNotFoundError for Package Data
Reading a bundled data file with a filesystem path works from a source checkout but fails once installed, because the file may live inside a zip or simply was never packaged. importlib.resources is the supported way - but the data must actually ship in the wheel.
What this error means
Code that loads a template/config/data file raises FileNotFoundError in CI after an install (or in a zipapp/Lambda), while it works when run from the repo. The data file is missing from the installed package or read by a fragile relative path.
FileNotFoundError: [Errno 2] No such file or directory:
'/usr/lib/python3.11/site-packages/myapp/data/config.yaml'Common causes
Data file not included in the wheel
Without declaring package data, the build excludes non-.py files. The import works but the data file is simply not present in the installed package.
Reading by filesystem path instead of resources
Using open(os.path.join(os.path.dirname(__file__), "data.yaml")) assumes an unpacked layout. In a zip import or relocated install, that path does not exist.
How to fix it
Include the data in the package
Declare package data so the files ship in the wheel.
[tool.setuptools.package-data]
myapp = ["data/*.yaml"]Read it via importlib.resources
Use the resources API so it works whether the package is on disk or zipped.
from importlib.resources import files
cfg = files("myapp.data").joinpath("config.yaml").read_text(encoding="utf-8")How to prevent it
- Declare every shipped data file as package data.
- Access bundled files with
importlib.resources, never raw paths. - Test against an installed wheel, not just the source tree.