Skip to content

Commit

Permalink
Optimize opening a file when it already exists on disk
Browse files Browse the repository at this point in the history
  • Loading branch information
brettcannon committed Oct 27, 2017
1 parent 539f3fe commit 818e58d
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions importlib_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,24 @@ def open(package: Package, file_name: FileName) -> BinaryIO:
"""Return a file-like object opened for binary-reading of the resource."""
file_name = _normalize_path(file_name)
package = _get_package(package)
package_path = os.path.dirname(os.path.abspath(package.__spec__.origin))
full_path = os.path.join(package_path, file_name)
# Just assume the loader is a resource loader; all the relevant
# importlib.machinery loaders are and an AttributeError for get_data() will
# make it clear what is needed from the loader.
loader = typing.cast(importlib.abc.ResourceLoader, package.__spec__.loader)
try:
data = loader.get_data(full_path)
except OSError:
package_name = package.__spec__.name
message = f'{file_name!r} resource not found in {package_name!r}'
raise FileNotFoundError(message)
package_path = pathlib.Path(package.__spec__.origin).resolve().parent
full_path = package_path / file_name
if full_path.exists():
return full_path.open('rb')
else:
return io.BytesIO(data)
# Just assume the loader is a resource loader; all the relevant
# importlib.machinery loaders are and an AttributeError for get_data()
# will make it clear what is needed from the loader.
loader = typing.cast(importlib.abc.ResourceLoader,
package.__spec__.loader)
try:
data = loader.get_data(str(full_path))
except OSError:
package_name = package.__spec__.name
message = f'{file_name!r} resource not found in {package_name!r}'
raise FileNotFoundError(message)
else:
return io.BytesIO(data)


def read(package: Package, file_name: FileName, encoding: str = 'utf-8',
Expand Down

0 comments on commit 818e58d

Please sign in to comment.