Skip to main content
3 of 3
include an equivalent
tshepang
  • 752
  • 3
  • 8

file handling

Instead of closing files yourself, have the with statement do it for you:

with open('filename') as filehandler:
    do_stuff(filehandler)

and not:

filehandler = open('filename')
do_stuff(filehandler)
filehandler.close()

Beyond saving you to have to close the file manually, the with statement also ensures the file will be closed even though exceptions rise during execution of do_stuff() function. That is, you get to avoid this ugliness:

filehandler = open('filename')
try:
    do_stuff(filehandler)
finally:
    filehandler.close()
tshepang
  • 752
  • 3
  • 8