import warnings
from ._common import files, as_file
_MISSING = object()
def open_binary(anchor, *path_names):
return _get_resource(anchor, path_names).open('rb')
def open_text(anchor, *path_names, encoding=_MISSING, errors='strict'):
encoding = _get_encoding_arg(path_names, encoding)
resource = _get_resource(anchor, path_names)
return resource.open('r', encoding=encoding, errors=errors)
def read_binary(anchor, *path_names):
return _get_resource(anchor, path_names).read_bytes()
def read_text(anchor, *path_names, encoding=_MISSING, errors='strict'):
encoding = _get_encoding_arg(path_names, encoding)
resource = _get_resource(anchor, path_names)
return resource.read_text(encoding=encoding, errors=errors)
def path(anchor, *path_names):
return as_file(_get_resource(anchor, path_names))
def is_resource(anchor, *path_names):
return _get_resource(anchor, path_names).is_file()
def contents(anchor, *path_names):
warnings.warn(
"importlib.resources.contents is deprecated. "
"Use files(anchor).iterdir() instead.",
DeprecationWarning,
stacklevel=1,
)
return (resource.name for resource in _get_resource(anchor, path_names).iterdir())
def _get_encoding_arg(path_names, encoding):
if encoding is _MISSING:
if len(path_names) > 1:
raise TypeError(
"'encoding' argument required with multiple path names",
)
else:
return 'utf-8'
return encoding
def _get_resource(anchor, path_names):
if anchor is None:
raise TypeError("anchor must be module or string, got None")
return files(anchor).joinpath(*path_names)