Python Language Context Managers (“with” Statement) Manage Resources


class File():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.open_file = open(self.filename, self.mode)
        return self.open_file

    def __exit__(self, *args):

__init__() method sets up the object, in this case setting up the file name and mode to open file. __enter__() opens and returns the file and __exit__() just closes it.

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement.

Use File class:

for _ in range(10000):
    with File('foo.txt', 'w') as f: