Python Forum

Full Version: with os.open?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have many cases where i need to call os.open, do something with that file descriptor, then close it. is there a way to do that using a with statement? what about using with with an object of my own creation? is there a specific method to implement?
See also contextlib.contextmanager for a simplified interface and also contextlib.closing and the like
import contextlib

@contextlib.contextmanager
def my_open(*args, **kwargs):
    fd = os.open(*args, **kwargs)
    try:
        yield fd
    finally:
        os.close(fd)

with my_open(my_thing) as desc:
    ...
Thanks, I didn't know that.