Monday, August 2, 2010

python: understanding the "with" statement/keyword

Consider some typical boilerplate code that opens a file (whose filename is passed as a command-line argument) in read-only mode, reads the file line-by-line and performs some operation on each line thus read:

fileIN = open(sys.argv[1], "r")
line = fileIN.readline()
while line:
    [do something with line]
    line = fileIN.readline()

From Python 2.5 onwards, this can be done more easily via the "with" statement:
with open(sys.argv[1], "r") as fileIN: 
    for line in fileIN: 
        [do something with line] 

The "with" statement reduces the line count from 5 to 3, and also makes the code more readable and human-friendly. It's more pythonic and intuitive.

source

No comments: