Skip to content

Instantly share code, notes, and snippets.

@JamesTheAwesomeDude
Last active March 11, 2024 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesTheAwesomeDude/93f6f5f359efc793afe5991143b9c874 to your computer and use it in GitHub Desktop.
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
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