Featured Post

Linux daemon using Python daemon with PID file and logging

The python-daemon package ( PyPI listing , Pagure repo ) is very useful. However, I feel it has suffered a bit from sparse documentation, an...

2014-09-01

Python's with statement

Old habits die hard. I learned a long time ago (Python 1.x) this pattern for opening and operating on files:

    try:    
        f = open("filename.txt", "ro")
        try:
            for l in f:
                print l
        finally:
            f.close()
    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)

Since Python 2.6, the with statement does this automatically:

    with open("filename.txt", "ro") as f:
        for l in f:
            print l

The with statement works with some other classes, too.

PS Blogger really needs a code block style.