Home >Backend Development >Python Tutorial >How to Access Static Files Embedded in Python Packages?
Retrieving Static Files Within Python Packages
Issue:
How to retrieve a file packaged within a Python package, given that it is not accessible via the standard file path methods?
Package Structure:
Consider a package structure where templates are stored in a nested "templates" folder:
<package> |-- <module> |-- templates |-- temp_file
Solution:
There are several methods to retrieve the file:
1. Using importlib.resources (Python 3.7 ):
from importlib import resources as impresources resource_package = __name__ resource_path = "templates/temp_file" try: inp_file = impresources.files(resource_package) / resource_path with inp_file.open("rb") as f: template = f.read() except AttributeError: # Python < 3.9 template = impresources.read_text(resource_package, resource_path)
2. Using pkg_resources (setuptools):
import pkg_resources resource_package = __name__ resource_path = "/".join(("templates", "temp_file")) template = pkg_resources.resource_string(resource_package, resource_path)
Details:
The above is the detailed content of How to Access Static Files Embedded in Python Packages?. For more information, please follow other related articles on the PHP Chinese website!