@@ -919,13 +919,13 @@ def __exit__(self, exc_type, exc_value, traceback):
919
919
def open_read (filename : ReadableFileLike ) -> Iterable [str ]:
920
920
"""Open the given file, list of files or files matching the given glob and read lines.
921
921
922
- `filename` is None or "-" -> reads from stdin
923
- `filename` is a Path / str -> interprets filename as a glob and open files matching it
924
- `filename` is a list -> opens sequentially all files from the list using `open_read`
925
- `filename` is something else -> returns the object wrapped in a `nullcontext`
926
- This allows to pass already openened files or iterables.
922
+ `filename` is None or "-" -> reads from stdin
923
+ `filename` is a Path / str -> interprets filename as a glob and open files matching it
924
+ `filename` is a list -> opens sequentially all files from the list using `open_read`
925
+ `filename` is something else -> returns the object wrapped in a `nullcontext`
926
+ This allows to pass already openened files or iterables.
927
927
928
- `open_read` will decompress gzip files, given they have ".gz" suffix.
928
+ `open_read` will decompress gzip files, given they have ".gz" suffix.
929
929
"""
930
930
if filename is None :
931
931
return sys .stdin
@@ -954,14 +954,22 @@ def open_read(filename: ReadableFileLike) -> Iterable[str]:
954
954
filename = files [0 ]
955
955
956
956
assert isinstance (filename , Path )
957
- mode = "rt"
958
- logging .getLogger (__name__ ).info (f"Opening { filename } with mode { mode } " )
959
- if filename .suffix == ".gz" :
960
- return gzip .open (filename , mode )
961
957
962
958
if filename .name .endswith ("]" ):
963
959
return block_reader (filename )
964
- return open (filename , mode )
960
+
961
+ logging .getLogger (__name__ ).info (f"Opening { filename } with mode 'rt'" )
962
+ if filename .suffix == ".gz" :
963
+ file : TextIO = gzip .open (filename , "rt" ) # type: ignore
964
+ else :
965
+ file = open (filename , "rt" )
966
+
967
+ return _close_when_exhausted (file )
968
+
969
+
970
+ def _close_when_exhausted (file : TextIO ) -> Iterable [str ]:
971
+ with file :
972
+ yield from file
965
973
966
974
967
975
def _yield_from (files : list ) -> Iterable [str ]:
0 commit comments