File tree Expand file tree Collapse file tree 1 file changed +18
-4
lines changed
Expand file tree Collapse file tree 1 file changed +18
-4
lines changed Original file line number Diff line number Diff line change @@ -40,10 +40,24 @@ def open_file_for_reading(input_file: _TextIOSource) -> ContextManager[IO[str]]:
4040 if not zipfile .is_zipfile (p ):
4141 print (f"Parent { p } is not ZIP file." )
4242 continue
43- zf = zipfile .ZipFile (p )
44- path_string = Path .as_posix (input_file .relative_to (p ))
45- stream = zf .open (path_string )
46- return io .TextIOWrapper (stream )
43+ # Create a custom context manager that closes both
44+ # the ZIP file and the stream when the context is exited.
45+ @contextlib .contextmanager
46+ def zip_file_reader ():
47+ zf = zipfile .ZipFile (p )
48+ try :
49+ path_string = Path .as_posix (input_file .relative_to (p ))
50+ stream = zf .open (path_string )
51+ wrapped = io .TextIOWrapper (stream )
52+ try :
53+ yield wrapped
54+ finally :
55+ wrapped .close ()
56+ stream .close ()
57+ finally :
58+ zf .close ()
59+
60+ return zip_file_reader ()
4761
4862 return contextlib .closing (open (input_file , 'rt' ))
4963
You can’t perform that action at this time.
0 commit comments