문제

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()
도움이 되었습니까?

해결책

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"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top