Skip to main content
1 of 3
tshepang
  • 752
  • 3
  • 8

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, the with statement also ensures the file will be closed even though exceptions rise to execution of do_stuff() function.

tshepang
  • 752
  • 3
  • 8