with statements and exceptions

John Salerno johnjsal at NOSPAMgmail.com
Wed Oct 25 15:34:48 EDT 2006


I'm thinking about using a with statement for opening a file, instead of 
the usual try/except block, but I don't understand where you handle an 
exception if the file doesn't open. For example:

with open('myfile', 'r'):
     BLOCK

I assume that BLOCK can/will contain all the other stuff you want to do, 
which may involve try/except blocks, but what if the initial open() call 
fails (for lack of file, etc.)? Is this the purpose of the with 
statement, to handle this itself? Is there still some way that I can 
respond to this and show the user an error message?

Thanks.



More information about the Python-list mailing list