from pathlib import Path

class Context:
    def __init__(self):
        print("Constructing context")

    def __enter__(self):
        print("Entering context")
        return "Coucou"

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting context", exc_type)

# with Context() as ctx:
#     print("In context", ctx)


from tempfile import NamedTemporaryFile
import os

class InplaceEdit:
    def __init__(self, filename, encoding="UTF-8"):
        self.filename = filename
        self.ifile = open(filename, encoding=encoding)
        self.encoding = encoding
        self.tmpfile = NamedTemporaryFile(mode="w", delete=False, encoding=encoding, dir=Path(filename).parent)

    def __enter__(self):
        return self.ifile, self.tmpfile

    def __exit__(self, typ, value, tb):
        self.ifile.close()
        self.tmpfile.close()
        if typ is None:
            os.rename(self.tmpfile.name, self.filename)
        else:
            os.unlink(self.tmpfile.name)

# with open("/etc/hosts") as hosts, open("/etc/shadow") as shadow:
#     ...

with InplaceEdit("hosts.txt") as (ifile, ofile):
    for line in ifile:
        ofile.write(line.replace("www.mdk.fr", "mdk.fr"))
