with statements and exceptions

J

John Salerno

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.
 
J

John Salerno

John said:
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.
 
P

Paul Rubin

John Salerno said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top