To read a file that is located within a Python package, there are several approaches available. One recommended method involves utilizing the importlib.resources module introduced in Python 3.7.
from importlib import resources from . import templates inp_file = resources.files(templates) / 'temp_file' # open the file using the file-like stream context manager with inp_file.open("rt") as f: template = f.read()
This approach offers several advantages over the legacy pkg_resources module. It is more performant, safer, requires no path manipulation, and relies solely on the standard library.
For those using Python versions prior to 3.7, or for backward compatibility, the importlib_resources library can be backported.
try: from importlib import resources except ImportError: import importlib_resources from . import templates inp_file = resources.files(templates) / 'temp_file' try: with inp_file.open("rb") as f: # or "rt" as text file with universal newlines template = f.read() except AttributeError: # Python < PY3.9, fall back to method deprecated in PY3.11. template = resources.read_text(templates, 'temp_file')
In this context, the resources.files() function returns a PathLike object that represents the path to the target file. The resource_name parameter now represents the filename within the package, without any path separators. To access a file within the current module, specify __package__ as the package argument (e.g., resources.read_text(__package__, 'temp_file')).
The above is the detailed content of How Can I Access Static Files Inside a Python Package?. For more information, please follow other related articles on the PHP Chinese website!