Python Forum
what works with the with statement?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what works with the with statement?
#7
You could wrap it in a context manager
import contextlib
import os

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

s = b'hello world'
with osopen('foo.txt', os.O_WRONLY|os.O_CREAT, 0o666) as fd:
    while s:
        n = os.write(fd, s)
        s = s[n:]
Skaperen and snippsat like this post
Reply


Messages In This Thread
what works with the with statement? - by Skaperen - Jan-02-2022, 11:19 PM
RE: what works with the with statement? - by Gribouillis - Jan-05-2022, 07:49 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020