from __future__ import with_statementtry: with open( "a.txt" ) as f : print f.readlines()except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available print 'oops'
如果您希望通过打开调用与工作代码进行不同的错误处理,则可以执行以下操作:
try: f = open('foo.txt')except IOError: print('error')else: with f: print f.readlines()


