Tuesday, January 8, 2013

[Level 2] Implement with syntax in Python.

#!/bin/env python
class myOpen(object):
    def __init__(self, filename, readwrite):
        self.__filename = filename
        self.__readwrite = readwrite
        self.__fd = None

    def __enter__(self):
        self.__fd = open(self.__filename, self.__readwrite)
        return self.__fd

    def __exit__(self, *args):
        self.__fd.close()

with myOpen('/tmp/my.txt', 'r') as f:
    print f.readlines()

with myOpen('/tmp/hello.txt', 'w') as f:
    f.write('hello world!\n')
$ ./test.py 
['-rwxr--r-- 1 stanley stanley   846 2012-12-26 13:07 ./c.py\n', '-rwxr--r-- 1 stanley stanley   486 2013-01-08 17:54 ./test.py\n']
$ cat ./my.txt 
-rwxr--r-- 1 stanley stanley   846 2012-12-26 13:07 ./c.py
-rwxr--r-- 1 stanley stanley   486 2013-01-08 17:54 ./test.py
$ cat ./hello.txt 
hello world!


Wish this helps.

regards,
Stanley Huang