views:

74

answers:

1

With having the with statement, is there ever a need to open a file/check for exceptions/do manual closing of resources, like in

try:
  f = open('myfile.txt')

  for line in f:
    print line
except IOError:
  print 'Could not open/read file'
finally:
  f.close()
+5  A: 

Your current code tries to handle the exception of the file not being found, or of insufficient access permissions etc., which a with open(file) as f: block wouldn't have done.

Also, in this case, the finally: block would have raised a NameError since f wouldn't have been defined.

In a with block, any exception (of whatever kind, maybe a division by zero in your code) that occurs within the block will still be raised, but even if you don't handle it, your file will always be closed properly. That's something entirely different.

What you want is probably:

try:
    with open("myfile.txt") as f:
        do_Stuff()  # even if this raises an exception, f will be closed.
except IOError:
    print "Couldn't open/read myfile.txt"
Tim Pietzcker