Last active
March 11, 2024 19:11
-
-
Save JamesTheAwesomeDude/93f6f5f359efc793afe5991143b9c874 to your computer and use it in GitHub Desktop.
Safely open path if not already open, but don't mess with pre-openend files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager, ExitStack | |
import io | |
__all__ = ['maybe_open'] | |
@contextmanager | |
def maybe_open(file_or_path, mode, *, **k, mode_strict=False): | |
with ExitStack() as _inner_ctx: | |
if isinstance(file_or_path, io.IOBase): | |
file = file_or_path | |
else: | |
file = _inner_ctx.enter_context(open(file_or_path, mode, **k)) | |
if mode_strict and (file.mode != mode): | |
raise TypeError(f'File is in wrong mode, {file.mode!r}') | |
yield file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment