Showing posts with label with statement. Show all posts
Showing posts with label with statement. Show all posts

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.