469,903 Members | 1,667 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,903 developers. It's quick & easy.

with statements and exceptions

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.
Oct 25 '06 #1
2 996
John Salerno wrote:
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.
Let me just toss this in as well:

def create_sql_script(self):
with open('labtables.sql') as sql_script:
return sql_script.read()

Does the file still get closed even though I have a return statement
inside the with block?

Thanks.
Oct 25 '06 #2
John Salerno <jo******@NOSPAMgmail.comwrites:
def create_sql_script(self):
with open('labtables.sql') as sql_script:
return sql_script.read()

Does the file still get closed even though I have a return statement
inside the with block?
Yes, I think so. I'm not running 2.5 yet but this is supposed to be
the idea of the with statement. As for the open failing, you'd deal
with that using try/except around the whole thing.

http://www.python.org/dev/peps/pep-0343/ explains the with statement
in detail.
Oct 25 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by pythos | last post: by
8 posts views Thread by John B | last post: by
9 posts views Thread by John Salerno | last post: by
2 posts views Thread by ojorus | last post: by
3 posts views Thread by Doug | last post: by
3 posts views Thread by =?Utf-8?B?WFNsZXI=?= | last post: by
28 posts views Thread by Christoph Zwerschke | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.