Skip to content

Commit 818e58d

Browse files
committed
Optimize opening a file when it already exists on disk
1 parent 539f3fe commit 818e58d

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

importlib_resources/__init__.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,20 +46,24 @@ def open(package: Package, file_name: FileName) -> BinaryIO:
4646
"""Return a file-like object opened for binary-reading of the resource."""
4747
file_name = _normalize_path(file_name)
4848
package = _get_package(package)
49-
package_path = os.path.dirname(os.path.abspath(package.__spec__.origin))
50-
full_path = os.path.join(package_path, file_name)
51-
# Just assume the loader is a resource loader; all the relevant
52-
# importlib.machinery loaders are and an AttributeError for get_data() will
53-
# make it clear what is needed from the loader.
54-
loader = typing.cast(importlib.abc.ResourceLoader, package.__spec__.loader)
55-
try:
56-
data = loader.get_data(full_path)
57-
except OSError:
58-
package_name = package.__spec__.name
59-
message = f'{file_name!r} resource not found in {package_name!r}'
60-
raise FileNotFoundError(message)
49+
package_path = pathlib.Path(package.__spec__.origin).resolve().parent
50+
full_path = package_path / file_name
51+
if full_path.exists():
52+
return full_path.open('rb')
6153
else:
62-
return io.BytesIO(data)
54+
# Just assume the loader is a resource loader; all the relevant
55+
# importlib.machinery loaders are and an AttributeError for get_data()
56+
# will make it clear what is needed from the loader.
57+
loader = typing.cast(importlib.abc.ResourceLoader,
58+
package.__spec__.loader)
59+
try:
60+
data = loader.get_data(str(full_path))
61+
except OSError:
62+
package_name = package.__spec__.name
63+
message = f'{file_name!r} resource not found in {package_name!r}'
64+
raise FileNotFoundError(message)
65+
else:
66+
return io.BytesIO(data)
6367

6468

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

0 commit comments

Comments
 (0)