Sometimes, we want to read a static file from inside a Python package.
In this article, we’ll look at how to read a static file from inside a Python package.
How to read a static file from inside a Python package?
To read a static file from inside a Python package, we can use the importlib.resources
library.
For instance, we write
try:
import importlib.resources as pkg_resources
except ImportError:
import importlib_resources as pkg_resources
from . import templates
template = pkg_resources.read_text(templates, 'temp_file')
to import our package with
from . import templates
Then we read our static file with
template = pkg_resources.read_text(templates, 'temp_file')
We can also open the static file as a file with
template = pkg_resources.open_text(templates, 'temp_file')
Conclusion
To read a static file from inside a Python package, we can use the importlib.resources
library.