views:

922

answers:

4

Hello,

To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:

with open("a.txt") as f:
    print f.readlines()

I really want to handle 'file not found exception' in order to do somehing. But I can't write

with open("a.txt") as f:
    print f.readlines()
except:
    print 'oops'

and can't write

with open("a.txt") as f:
    print f.readlines()
else:
    print 'oops'

enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?

+21  A: 
from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'
Douglas Leeder
thanks, it was a method redifinition bug ^_^. Actually works.
Eye of Hell
Could also generate an OSError.
MizardX
MizardX: it also can generate a WindowsError, ergo the edit :)
ΤΖΩΤΖΙΟΥ
Looks good to me...
Douglas Leeder
ΤΖΩΤΖΙΟΥ: WindowsError is a subclass of OSError. But EnvironmentError will do.
MizardX
+2  A: 

I just tried, enclosing the with in a try/except works fine.

try:
  with open("dummy.txt", "r") as f:
    print(f.readlines())
except:
  print("oops")
Loïc Wolff
-1: bare except is always a bad idea, this really shouldn't be given as example to a newbie.
nosklo
A: 
with open("x.txt") as f:
    data = f.read()
    do something with data
Younes
-1: Doesn't answer the OP's question.
MizardX
fix the white space plz
hasen j
-1: not an answer
nosklo
+2  A: 

This code works fine in python 2.5.1:

from __future__ import with_statement

try:
    with open('non-existent.txt') as f:
        print f.readlines()
except:
    print "Exception"
Eugene Morozov
-1: bare except is always a bad idea, this really shouldn't be given as example to a newbie.
nosklo