@@ -50,8 +50,7 @@ def _normalize_path(path) -> str:
50
50
parent , file_name = os .path .split (str_path )
51
51
if parent :
52
52
raise ValueError ('{!r} must be only a file name' .format (path ))
53
- else :
54
- return file_name
53
+ return file_name
55
54
56
55
57
56
def _get_resource_reader (
@@ -96,8 +95,7 @@ def open_binary(package: Package, resource: Resource) -> BinaryIO:
96
95
message = '{!r} resource not found in {!r}' .format (
97
96
resource , package_name )
98
97
raise FileNotFoundError (message )
99
- else :
100
- return BytesIO (data )
98
+ return BytesIO (data )
101
99
102
100
103
101
def open_text (package : Package ,
@@ -146,33 +144,34 @@ def path(package: Package, resource: Resource) -> Iterator[Path]:
146
144
package = _get_package (package )
147
145
reader = _get_resource_reader (package )
148
146
if reader is not None :
149
- try :
147
+ with suppress ( FileNotFoundError ) :
150
148
yield Path (reader .resource_path (resource ))
151
149
return
152
- except FileNotFoundError :
153
- pass
154
150
# Fall-through for both the lack of resource_path() *and* if
155
151
# resource_path() raises FileNotFoundError.
156
152
package_directory = Path (package .__spec__ .origin ).parent
157
153
file_path = package_directory / resource
154
+ # If the file actually exists on the file system, just return it.
158
155
if file_path .exists ():
159
156
yield file_path
160
- else :
161
- with open_binary (package , resource ) as fp :
162
- data = fp .read ()
163
- # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'
164
- # blocks due to the need to close the temporary file to work on
165
- # Windows properly.
166
- fd , raw_path = tempfile .mkstemp ()
167
- try :
168
- os .write (fd , data )
169
- os .close (fd )
170
- yield Path (raw_path )
171
- finally :
172
- try :
173
- os .remove (raw_path )
174
- except FileNotFoundError :
175
- pass
157
+ return
158
+
159
+ # Otherwise, it's probably in a zip file, so we need to create a temporary
160
+ # file and copy the contents into that file, hence the contextmanager to
161
+ # clean up the temp file resource.
162
+ with open_binary (package , resource ) as fp :
163
+ data = fp .read ()
164
+ # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'
165
+ # blocks due to the need to close the temporary file to work on
166
+ # Windows properly.
167
+ fd , raw_path = tempfile .mkstemp ()
168
+ try :
169
+ os .write (fd , data )
170
+ os .close (fd )
171
+ yield Path (raw_path )
172
+ finally :
173
+ with suppress (FileNotFoundError ):
174
+ os .remove (raw_path )
176
175
177
176
178
177
def is_resource (package : Package , name : str ) -> bool :
0 commit comments