Skip to content
This repository was archived by the owner on Oct 31, 2023. It is now read-only.

Commit ae24701

Browse files
committed
fix not closing files when using open_read
1 parent d31baa5 commit ae24701

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

cc_net/jsonql.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -919,13 +919,13 @@ def __exit__(self, exc_type, exc_value, traceback):
919919
def open_read(filename: ReadableFileLike) -> Iterable[str]:
920920
"""Open the given file, list of files or files matching the given glob and read lines.
921921
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.
927927
928-
`open_read` will decompress gzip files, given they have ".gz" suffix.
928+
`open_read` will decompress gzip files, given they have ".gz" suffix.
929929
"""
930930
if filename is None:
931931
return sys.stdin
@@ -954,14 +954,22 @@ def open_read(filename: ReadableFileLike) -> Iterable[str]:
954954
filename = files[0]
955955

956956
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)
961957

962958
if filename.name.endswith("]"):
963959
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
965973

966974

967975
def _yield_from(files: list) -> Iterable[str]:

0 commit comments

Comments
 (0)